假设我有以下字符串:
name1=gil;name2=orit;
我希望找到name=value
的所有匹配项,并确保整个字符串都与该模式匹配。
因此,我做了以下工作:
模式p= Pattern.compile("^((\w+)=(\w+);)*$");匹配器m=p.matcher(行);if (!m.matches()) { return false;}
name=value
Pattern p= Pattern.compile("(\w+)=(\w+);");Matcher m=p.matcher(行);while (m.find()) { map.put(m.group(1),m.group(2));}
有没有什么方法可以用一个正则表达式来做到这一点?
发布于 2013-05-29 23:03:26
您可以通过以下方法使用一个正则表达式验证和迭代匹配:
的\G
来确保匹配之间没有不匹配的字符(例如,\G
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!");
发布于 2013-05-29 22:52:16
您必须为"^“和"$”启用多行模式才能按预期工作。
Pattern p = Pattern.compile("^(?:(\\w+)=(\\w+);)*$", Pattern.MULTILINE);
while (m.find()) {
for (int i = 0; i < m.groupCount() - 2; i += 2) {
map.put(m.group(i + 1), m.group(i + 2));
}
}
注释正确的地方,您仍然需要遍历每一行的匹配组,并将外部组设置为非捕获组(?:...)
。
发布于 2013-05-29 22:57:25
String example = "name1=gil;name2=orit;";
Pattern pattern = Pattern.compile("((name[0-9]+?=(.+?);))+?");
Matcher matcher = pattern.matcher(example);
// verifies full match
if (matcher.matches()) {
System.out.println("Whole String matched: " + matcher.group());
// resets matcher
matcher.reset();
// iterates over found
while (matcher.find()) {
System.out.println("\tFound: " + matcher.group(2));
System.out.println("\t--> name is: " + matcher.group(3));
}
}
输出:
Whole String matched: name1=gil;name2=orit;
Found: name1=gil;
--> name is: gil
Found: name2=orit;
--> name is: orit
https://stackoverflow.com/questions/16817031
复制相似问题