[英]Find pattern in string with regex -> how to improve my solution
我想解析一个字符串并获取"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)
访问由捕获组匹配的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 _
的情况下您的预期输出是什么。 并且是否要允许下划线_
成为输出的一部分?
使用group(1)
而不是group()
因为group()
将为您提供整个模式,而不是匹配的组。
参考: http : //docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group(int)
您可以定义所需的组,因为您已经在使用括号。 您只需要稍微调整一下模式即可。
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));
}
"xyz_stringIAmLookingFor_zxy".replaceAll("_(\\w)*_", "$1");
将用括号将此组替换所有内容
一个更简单的正则表达式,不需要组:
"(?<=_)[^_]*"
如果您想要更严格:
"(?<=_)[^_]+(?=_)"
尝试
String s = "xyz_stringIAmLookingFor_zxy".replaceAll(".*_(\\w*)_.*", "$1");
System.out.println(s);
输出
stringIAmLookingFor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.