gpt4 book ai didi

java - 使用正则表达式在字符串中查找模式 -> 如何改进我的解决方案

转载 作者:行者123 更新时间:2023-11-29 10:16:51 24 4
gpt4 key购买 nike

我想解析一个字符串并获取它的 "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);
}

最佳答案

解决方案(部分)

另请查看下一部分。不要只阅读此处的解决方案。

稍微修改一下代码:

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 个的情况下您的预期输出是什么。是否允许下划线 _ 成为输出的一部分?

关于java - 使用正则表达式在字符串中查找模式 -> 如何改进我的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15523299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com