假设我有以下字符串:
name1=gil;name2=orit;
我想查找 name=value
的所有匹配项,并确保整个字符串与模式匹配。
所以我做了以下事情:
确保整个模式与我想要的匹配。
Pattern p = Pattern.compile("^((\\w+)=(\\w+);)*$"); Matcher m = p.matcher(line); if (!m.matches()) { return false; }
遍历模式
name=value
Pattern p = Pattern.compile("(\\w+)=(\\w+);"); Matcher m = p.matcher(line); while (m.find()) { map.put(m.group(1), m.group(2)); }
有没有办法用一个正则表达式来做到这一点?
最佳答案
您可以通过以下方式使用一个正则表达式验证和迭代匹配项:
通过在我们的开头放置一个
\G
来确保匹配之间没有不匹配的字符(例如name1=x;;name2=y;
)正则表达式,表示 "the end of the previous match" .通过将字符串的长度与
Matcher.end()
进行比较来检查我们是否在最后一场比赛中到达了字符串的末尾,它返回匹配的最后一个字符之后的偏移量。
类似:
String line = "name1=gil;name2=orit;";
Pattern p = Pattern.compile("\\G(\\w+)=(\\w+);");
Matcher m = p.matcher(line);
int lastMatchPos = 0;
while (m.find()) {
System.out.println(m.group(1));
System.out.println(m.group(2));
lastMatchPos = m.end();
}
if (lastMatchPos != line.length())
System.out.println("Invalid string!");
关于java - 如何迭代正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16817031/