Java正则表达式匹配元组
我需要从字符串中提取元组 e、 g.Java正则表达式匹配元组,java,regex,string,tuples,Java,Regex,String,Tuples,我需要从字符串中提取元组 e、 g.(1,1,A)(2,1,B)(1,1,C)(1,1,D) 我想一些正则表达式是这样的: String tupleRegex = "(\\(\\d,\\d,\\w\\))*"; 会有用,但它只会给我第一个元组。什么是合适的正则表达式来匹配字符串中的所有元组。从正则表达式中删除*,并使用java.util.regex.Matcher迭代匹配: String input = "(1,1,A)(2,1,B)(1,1,C)(1,1,D)"; String tupleR
(1,1,A)(2,1,B)(1,1,C)(1,1,D)
我想一些正则表达式是这样的:
String tupleRegex = "(\\(\\d,\\d,\\w\\))*";
会有用,但它只会给我第一个元组。什么是合适的正则表达式来匹配字符串中的所有元组。从正则表达式中删除
*
,并使用java.util.regex.Matcher
迭代匹配:
String input = "(1,1,A)(2,1,B)(1,1,C)(1,1,D)";
String tupleRegex = "(\\(\\d,\\d,\\w\\))";
Pattern pattern = Pattern.compile(tupleRegex);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
System.out.println(matcher.group());
}
*
字符是匹配零个或多个元组的量词。因此,原始正则表达式将匹配整个输入字符串。使用string.split()
方法的单行解决方案,下面是模式(?!^\\()(?=\\()
输出:
[(1,1,A), (2,1,B), (1,1,C), (1,1,D)]
这里也是
模式说明:
(?! look ahead to see if there is not:
^ the beginning of the string
\( '('
) end of look-ahead
(?= look ahead to see if there is:
\( '('
) end of look-ahead
“它只是给了我第一个元组”我们能看看你的代码吗?如果我没有弄错的话,你的正则表达式应该匹配整个
(1,1,A)(2,1,B)(1,1,C)(1,1,D)
,在第一组中它应该包含最后一个元组(1,1,D)
,而不是第一个。你答案中的模式似乎很复杂,((\D\D\w))似乎也能工作。它寻找(
但不是开头的,拆分字符串。复杂吗?
(?! look ahead to see if there is not:
^ the beginning of the string
\( '('
) end of look-ahead
(?= look ahead to see if there is:
\( '('
) end of look-ahead