Matcher matcher = Pattern.compile("\\bwidth\\s*:\\s*(\\d+)px|\\bbackground\\s*:\\s*#([0-9A-Fa-f]+)").matcher(myString);
if (matcher.find()) {
System.out.println(matcher.group(2));
}
示例数据:
myString = width:17px;background:#555;float:left;
将产生null
。我想要的是:
matcher.group(1) = 17
matcher.group(2) = 555
我刚刚开始在Java上使用正则表达式,有什么帮助吗?
最佳答案
我建议稍微拆分一下。
与其构建一个大型的正则表达式(也许您想向字符串中添加更多规则?),不如将其分成多个部分:
String myString = "width:17px;background:#555;float:left;";
String[] sections = myString.split(";"); // split string in multiple sections
for (String section : sections) {
// check if this section contains a width definition
if (section.matches("width\\s*:\\s*(\\d+)px.*")) {
System.out.println("width: " + section.split(":")[1].trim());
}
// check if this section contains a background definition
if (section.matches("background\\s*:\\s*#[0-9A-Fa-f]+.*")) {
System.out.println("background: " + section.split(":")[1].trim());
}
...
}
关于java - 正则表达式捕获组在OR运算符之后返回为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14083628/