理解Java正则表达式模式示例
我有一个Java正则表达式示例,可以根据给定的模式从给定的输入字符串中提取内容:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternEx {
static Pattern PATTERN_ONE = Pattern.compile("^(/?test/[^/]+)/([^/]+)(/?.*)$");
static Pattern PATTERN_TWO = Pattern.compile("^(/?test)/([^/]+)(/?.*)$");
static Pattern[] PATTERNS = { PATTERN_ONE, PATTERN_TWO };
public static void main(String[] args) {
for (Pattern p : PATTERNS) {
Matcher m = p.matcher("/test/hello/world/checking/");
if (m.matches()) {
System.out.println(m.group(2));
}
}
}
}
该程序的输出为:
world
hello
我已经浏览了Java doc for regular expressions,根据文档,我可以看到这里的模式使用了“Capturing Groups”
但我无法理解我的示例中的模式是如何工作的,它的含义是什么,以及它如何能够从输入字符串中提取数据。有人能帮我理解这个代码吗
# 1 楼答案
希望这有助于:
模式1:
^(/?test/[^/]+)/([^/]+)(/?.*)$
模式2:
^(/?test)/([^/]+)(/?.*)$
提示:
^,$,?,,*,[]-regex操作员,你可以用谷歌搜索他们的意思