我有一个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"
但我无法理解我的示例中的模式是如何工作的,它的含义是什么以及它如何从输入字符串中提取数据。有人可以帮助我理解这段代码。
答案 0 :(得分:2)
希望这会有所帮助:
模式1:^(/?test/[^/]+)/([^/]+)(/?.*)$
group 1: (/?test/[^/]+) = "/test/hello"
group 2: ([^/]+) = "world"
group 3: (/?.*) = "/checking/"
模式2:^(/?test)/([^/]+)(/?.*)$
group 1: (/?test) = "/test"
group 2: ([^/]+) = "hello"
group 3: (/?.*) = "world/checking/"
提示:
/?test - the slash is optional = "test", "/test"
[^/] - anything else than a slash = "hello", "world", "$#* abc",...
[^/]+ - the plus stands for 1 or more times = "a", "aa",...
/?.* - optional slash and any character 0 or more times = "","/","a","/a",...
^,$,?,。,*,[] - 正则表达式运算符,你可以谷歌的意思。