【发布时间】:2015-01-15 20:18:12
【问题描述】:
这里是the regex 我遇到了问题:^(?:(\S+?)(?:\s+|\s*$))。
我正在尝试在以下String 中匹配此模式的 3 次出现:
-execution thisIsTest1 thisIsTest2。这是获取第一个 numberOfArgs 元素并返回填充匹配项的 List<String> 的方法。问题是:返回的List的大小是1....循环总是迭代一次然后退出...
private final String arguments="-execution thisIsTest1 thisIsTest2";
/**
* Split the first N arguments separated with one or more whitespaces.
* @return the array of size numberOfArgs containing the matched elements.
*/
...
public List<String> fragmentFirstN(int numberOfArgs){
Pattern patt = Pattern.compile("^(?:(\\S+?)(?:\\s+|\\s*$))",Pattern.MULTILINE);
Matcher matc = patt.matcher(arguments);
ArrayList<String> args = new ArrayList<>();
logg.info(arguments);
int i = 0;
while(matc.find()&&i<numberOfArgs){
args.add(matc.group(1));
i++;
}
return args;
}
这里是测试类:
private String[] argArr={"-execution",
"thisIsTest1",
"thisIsTest2"
};
...
@Test
public void testFragmentFirstN() throws Exception {
List<String> arr = test.fragmentFirstN(3);
assertNotNull(arr);
System.out.println(arr); ----> prints : [-execution]
System.out.println(test.getArguments()); ----> prints : -execution thisIsTest1 thisIsTest2 <-----
assertEquals(argArr[0],arr.get(0));
--->assertEquals(argArr[1],arr.get(1));<---- IndexOutOfBoundException : Index: 1, Size: 1
assertEquals(argArr[2],arr.get(2));
assertEquals(3,arr.size());
}
我认为Matcher#find() 在循环时会匹配所有可能的字符序列。我错过了什么?
【问题讨论】:
-
我认为答案是
^匹配输入字符串的开头,这意味着find只会找到第一个--跳过它之后,你不再在输入字符串的开头。我相信有一个正则表达式命令或Matcher方法来移动锚点,使其与前一个find停止的点相匹配,但我需要检查文档,因为我不记得了我的头顶。 -
尝试使用
\G代替^(即Java 字符串文字中的\\G)。 -
@ajb :在这里!我怎么会错过它...非常感谢您的帮助。