我尝试使用正则表达式解析字符串以从中获取参数。 例如:
String: "TestStringpart1 with second test part2" Result should be: String[] {"part1", "part2"} Regexp: "TestString(.*?) with second test (.*?)"
我的测试代码是:
String regexp = "TestString(.*?) with second test (.*?)"; String res = "TestStringpart1 with second test part2"; Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(res); int i = 0; while(matcher.find()) { i++; System.out.println(matcher.group(i)); }
但它只输出“part1” 有人可以给我提示吗?
谢谢
最佳答案
可能是一些修复正则表达式
String regexp = "TestString(.*?) with second test (.*)";
并更改 println 代码..
if (matcher.find())
for (int i = 1; i <= matcher.groupCount(); ++i)
System.out.println(matcher.group(i));
关于使用正则表达式解析 Java 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1318137/