1

我想解析一个字符串并获取它的-part,它在结尾和开头"stringIAmLookingFor"被包围。"\_"我正在使用正则表达式来匹配它,然后"\_"在找到的字符串中删除。这是有效的,但我想知道是否有更优雅的方法来解决这个问题?

String test = "xyz_stringIAmLookingFor_zxy";
Pattern p = Pattern.compile("_(\\w)*_");
Matcher m = p.matcher(test);
while (m.find()) { // find next match
    String match = m.group();
    match = match.replaceAll("_", "");
    System.out.println(match);
}
4

6 回答 6

6

解决方案(部分)

另请检查下一节。不要只是在这里阅读解决方案。

只需稍微修改您的代码:

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 个的情况,我不知道您的预期输出是什么。你想让下划线_成为输出的一部分吗?

于 2013-03-20T12:18:31.383 回答
1

使用group(1)而不是group()因为group()将获得整个模式而不是匹配组。

参考:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group(int)

于 2013-03-20T12:20:03.820 回答
1

你可以定义你真正想要的组,因为你已经在使用括号了。你只需要稍微调整一下你的模式。

String test = "xyz_stringIAmLookingFor_zxy";
Pattern p = Pattern.compile("_(\\w*)_");
Matcher m = p.matcher(test);
while (m.find()) { // find next match
    System.out.println(m.group(1));
}
于 2013-03-20T12:21:28.370 回答
0
"xyz_stringIAmLookingFor_zxy".replaceAll("_(\\w)*_", "$1");

将用括号中的该组替换所有内容

于 2013-03-20T12:20:15.160 回答
0

一个更简单的正则表达式,不需要组:

"(?<=_)[^_]*"

如果你想要更严格:

"(?<=_)[^_]+(?=_)"
于 2013-03-20T12:21:15.017 回答
0

尝试

    String s = "xyz_stringIAmLookingFor_zxy".replaceAll(".*_(\\w*)_.*", "$1");
    System.out.println(s);

输出

stringIAmLookingFor
于 2013-03-20T12:22:25.203 回答