解决方案(部分)
另请检查下一节。不要只是在这里阅读解决方案。
只需稍微修改您的代码:
String test = "xyz_stringIAmLookingFor_zxy";
// Make the capturing group capture the text in between (\w*)
// A capturing group is enclosed in (pattern), denoting the part of the
// pattern whose text you want to get separately from the main match.
// Note that there is also non-capturing group (?:pattern), whose text
// you don't need to capture.
Pattern p = Pattern.compile("_(\\w*)_");
Matcher m = p.matcher(test);
while (m.find()) { // find next match
// The text is in the capturing group numbered 1
// The numbering is by counting the number of opening
// parentheses that makes up a capturing group, until
// the group that you are interested in.
String match = m.group(1);
System.out.println(match);
}
Matcher.group()
, 不带任何参数将返回与整个正则表达式模式匹配的文本。Matcher.group(int group)
将返回与指定组号的捕获组匹配的文本。
如果您使用的是 Java 7,则可以使用命名的捕获组,这会使代码更具可读性。捕获组匹配的字符串可以用Matcher.group(String name)
.
String test = "xyz_stringIAmLookingFor_zxy";
// (?<name>pattern) is similar to (pattern), just that you attach
// a name to it
// specialText is not a really good name, please use a more meaningful
// name in your actual code
Pattern p = Pattern.compile("_(?<specialText>\\w*)_");
Matcher m = p.matcher(test);
while (m.find()) { // find next match
// Access the text captured by the named capturing group
// using Matcher.group(String name)
String match = m.group("specialText");
System.out.println(match);
}
模式问题
请注意,\w
也匹配_
. _
您拥有的模式不明确,对于字符串中超过 2 个的情况,我不知道您的预期输出是什么。你想让下划线_
成为输出的一部分吗?