[英]Extract a String using RegEx
[0-6, 1-3][01-20, 22-23]22/123
From the above input, I would like to extract the following the following texts. 从以上输入中,我想摘录以下文本。
0-6, 1-3
01-20, 22-23
22
123
The following code snippets extracts the required texts excepts the first one. 以下代码段提取了除第一个文本外的所需文本。
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));
}
Output: 输出:
[0-6, 1-3][01-20, 22-23]22/123
[01-20, 22-23]
01-20, 22-23
22
123
Can you please help me to fix my regex pattern to extract the first part also(0-6, 1-3)? 您能帮我修复正则表达式模式以提取第一部分吗(0-6、1-3)?
您应该分别指定前两个组中的每个组:
Pattern depArrHours = Pattern.compile("^(\\[(.+)\\])(\\[(.+)\\])(.+)\\/(.+)$");
Try the pattern 尝试模式
\\[([^\\]]*)\\]|(([0-9]*)/([0-9]*))
and use it with matcher.find()
并与
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);
}
}
Output 产量
0-6, 1-3
01-20, 22-23
22
123
You could try specifying each (\\\\[(.+)\\\\])
separate instead of {2}
: 您可以尝试指定每个
(\\\\[(.+)\\\\])
而不是{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));
}
Output : 输出:
[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
Try, 尝试,
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());
}
Try 尝试
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));
}
The Regex \\\\[([^\\\\]]*)\\\\]|([0-9]*)/([0-9]*)
can be represented as 正则表达式
\\\\[([^\\\\]]*)\\\\]|([0-9]*)/([0-9]*)
可以表示为
Output : 输出 :
0-6, 1-3
01-20, 22-23
22
123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.