[0-6, 1-3][01-20, 22-23]22/123
从上面的输入中,我想提取以下文字。
0-6, 1-3
01-20, 22-23
22
123
以下代码片段提取除第一个之外的所需文本。
Pattern depArrHours = Pattern.compile("^(\\[(.+)\\]){2}(.+)\\/(.+)$");
Matcher matcher = depArrHours.matcher("[0-6, 1-3][01-20, 22-23]22/123");
if (matcher.matches()) {
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
}
输出:
[0-6, 1-3][01-20, 22-23]22/123
[01-20, 22-23]
01-20, 22-23
22
123
你能帮我修一下我的正则表达式以提取第一部分(0-6,1-3)吗?
答案 0 :(得分:1)
您应该分别指定前两组中的每一组:
Pattern depArrHours = Pattern.compile("^(\\[(.+)\\])(\\[(.+)\\])(.+)\\/(.+)$");
答案 1 :(得分:1)
尝试模式
\\[([^\\]]*)\\]|(([0-9]*)/([0-9]*))
并将其与matcher.find()
Pattern depArrHours = Pattern.compile("\\[([^\\]]*)\\]|(([0-9]*)/([0-9]*))");
Matcher matcher = depArrHours.matcher("[0-6, 1-3][01-20, 22-23]22/123");
while (matcher.find()) {
String group = matcher.group(1);
if (group == null) {
// matched 22/123
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
} else {
// matched [0-6, 1-3] or [01-20, 22-23]
System.out.println(group);
}
}
输出
0-6, 1-3
01-20, 22-23
22
123
答案 2 :(得分:1)
您可以尝试指定每个(\\[(.+)\\])
分开而不是{2}
:
Pattern depArrHours = Pattern.compile("^(\\[(.+)\\])(\\[(.+)\\])(.+)\\/(.+)$");
Matcher matcher = depArrHours.matcher("[0-6, 1-3][01-20, 22-23]22/123");
if (matcher.matches()) {
System.out.println(matcher.group(0));
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));
System.out.println(matcher.group(4));
System.out.println(matcher.group(5));
System.out.println(matcher.group(6));
}
输出:
[0-6, 1-3][01-20, 22-23]22/123
[0-6, 1-3]
0-6, 1-3
[01-20, 22-23]
01-20, 22-23
22
123
答案 3 :(得分:1)
尝试,
String input="[0-6, 1-3][01-20, 22-23]22/123";
String[] arr=input.replace('[', ' ').split("[\\]/]");
for (String string : arr) {
System.out.println(string.trim());
}
答案 4 :(得分:1)
尝试
String k ="[0-6, 1-3][01-20, 22-23]22/123";
Pattern p = Pattern.compile("\\[([^\\]]*)\\]|([0-9]*)/([0-9]*)");
Matcher m = p.matcher(k);
while(m.find()){
System.out.println((m.group(1)!=null)?m.group(1):m.group(2)+"\n"+m.group(3));
}
正则表达式\\[([^\\]]*)\\]|([0-9]*)/([0-9]*)
可以表示为
输出:
0-6, 1-3
01-20, 22-23
22
123