Java 正则表达式截取数字和数字范围
你可以使用正则表达式来实现该功能。下面是一个示例代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String input = 'Eth-Trunk0 trunk 1 10 21 23 40 100-102 200-204';
String pattern = '\b\d+(?:-\d+)?\b'; // 匹配数字或者数字范围的正则表达式
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(input);
StringBuilder output = new StringBuilder();
while (matcher.find()) {
output.append(matcher.group()).append(' ');
}
String result = output.toString().trim();
System.out.println(result);
}
}
输出结果为:10 21 23 40 100-102 200-204
原文地址: https://www.cveoy.top/t/topic/Lyo 著作权归作者所有。请勿转载和采集!