我有兴趣将这些数字放入String
的数组中,但无法正常使用正则表达式和组。
代码:
package regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex {
public static void main(String[] args) {
String s = "A: 123/456 BC: 78/90 NEw: 105 E: 0 BK: 10 None: 0%";
Pattern p = Pattern.compile("(\\w+): (\\d+)");
Matcher m = p.matcher(s);
String[] as = new String[7];
as[2] = m.group(); //array list??
for (int i = 2; i < 2; i++) {
System.out.println(as[i]);
}
}
}
答案 0 :(得分:1)
您需要更改
Pattern p = Pattern.compile("(\\w+): (\\d+)");
到
Pattern p = Pattern.compile("(\\w+): (\\d+/{0,1}\\d*%{0,1})");
答案 1 :(得分:1)
Matcher
无法按照您尝试使用它的方式运行。 group()
方法返回最后匹配的组。要实际告诉匹配器匹配某些内容,您需要先调用find()
。 find()
返回一个布尔值,告诉匹配器是否设法找到下一个匹配项,以便您可以循环遍历所有匹配项:
while (m.find()) {
String text = m.group();
// ...
}
答案 2 :(得分:1)
您可以尝试使用正则表达式:
(\w+): +(\S+)
e.g:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(\\w+): +(\\S+)");
public static void main(String[] args) {
String input = "A: 123/456 BC: 78/90 NEw: 105 E: 0 BK: 10 None: 0%";
Matcher matcher = REGEX_PATTERN.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
输出:
A: 123/456
BC: 78/90
NEw: 105
E: 0
BK: 10
None: 0%
如果您想使用matcher.group(1)
获取名称,matcher.group(2)
或号码。
private static final Pattern REGEX_PATTERN =
Pattern.compile("(\\w+): +(\\S+)");
public static void main(String[] args) {
String input = "A: 123/456 BC: 78/90 NEw: 105 E: 0 BK: 10 None: 0%";
Matcher matcher = REGEX_PATTERN.matcher(input);
while (matcher.find()) {
System.out.println("Name: " + matcher.group(1));
System.out.println("Number: " + matcher.group(2));
}
}
输出:
Name: A
Number: 123/456
Name: BC
Number: 78/90
Name: NEw
Number: 105
Name: E
Number: 0
Name: BK
Number: 10
Name: None
Number: 0%
答案 3 :(得分:0)
package regex;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex {
public static void main(String[] args) {
List<Map.Entry> l = new ArrayList<>();
String monitor = "A: 123/456 BC: 78/90 NEw: 105 E: 0 BK: 10 None: 0%";
Pattern outerPattern = Pattern.compile("(\\w+): (\\d+)");
Matcher outerMatcher = outerPattern.matcher(monitor);
String outerGroup = null;
int i = 0;
Pattern innerPattern;
Matcher innerMatcher;
String innerGroup = null;
while (outerMatcher.find()) {
outerGroup = outerMatcher.group();
System.out.println(outerGroup);
innerPattern = Pattern.compile("(\\w+): (\\d+)");
innerMatcher = innerPattern.matcher(outerGroup);
while (innerMatcher.find()) {
innerGroup = innerMatcher.group();
System.out.println(innerGroup);
Map.Entry<String, Integer> entr = new AbstractMap.SimpleEntry<>("exmpleString", 42);
l.add(entr);
}
}
}
}