在java中打印正则表达式匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/836704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print regex matches in java
提问by
So I have an IP address as a string.
I have this regex (\d{1-3})\.(\d{1-3})\.(\d{1-3})\.(\d{1-3})
How do I print the matching groups?
所以我有一个IP地址作为字符串。我有这个正则表达式(\d{1-3})\.(\d{1-3})\.(\d{1-3})\.(\d{1-3})
如何打印匹配的组?
Thanks!
谢谢!
采纳答案by Lieven Keersmaekers
import java.util.regex.*;
try {
Pattern regex = Pattern.compile("(\d\{1-3\})\.(\d\{1-3\})\.(\d\{1-3\})\.(\d\{1-3\})");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
for (int i = 1; i <= regexMatcher.groupCount(); i++) {
// matched text: regexMatcher.group(i)
// match start: regexMatcher.start(i)
// match end: regexMatcher.end(i)
}
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
回答by Mike Cornell
If you use Pattern and Matcher to do your regex, then you can ask the Matcher for each group using the group(int group)method
如果你使用 Pattern 和 Matcher 来做你的正则表达式,那么你可以使用group(int group)方法向每个组询问 Matcher
So:
所以:
Pattern p = Pattern.compile("(\d{1-3}).(\d{1-3}).(\d{1-3}).(\d{1-3})");
Matcher m = p.matcher("127.0.0.1");
if (m.matches()) {
System.out.print(m.group(1));
// m.group(0) is the entire matched item, not the first group.
// etc...
}