使用简单的java代码提取css属性值
请检查以下代码使用简单的java代码提取css属性值,java,regex,Java,Regex,请检查以下代码 Pattern pxPattern = Pattern.compile("^.*[0-9]+(%|pt|em).*$"); Matcher pxMatcher = pxPattern.matcher("onehellot455emwohellothree"); System.out.println(pxMatcher.matches()); System.out.println(pxMatcher.group(0)); 我想减去字符串445em。我正在使用代码检查css。意思是
Pattern pxPattern = Pattern.compile("^.*[0-9]+(%|pt|em).*$");
Matcher pxMatcher = pxPattern.matcher("onehellot455emwohellothree");
System.out.println(pxMatcher.matches());
System.out.println(pxMatcher.group(0));
我想减去字符串445em。我正在使用代码检查css。意思是我想提取
只有45em或50%这样的值
谢谢。首先,捕获的组位于组1中,而不是组0中。然后,您需要修改正则表达式以不使用这些数字,并将它们包含在组中。尝试:
Pattern pxPattern = Pattern.compile("^.*?([0-9]+(?:%|pt|em)).*$");
Matcher pxMatcher = pxPattern.matcher("onehellot455emwohellothree");
System.out.println(pxMatcher.matches());
System.out.println(pxMatcher.group(1));
编辑:
要从包含多个字符串的字符串中获取所有值,可以使用以下模式:
Pattern pxPattern = Pattern.compile("[0-9]+(?:%|pt|em)");
Matcher pxMatcher = pxPattern.matcher("margin: 0pt, 6em, 5%, 2pt");
List<String> propertyValues = new ArrayList<String>();
while (pxMatcher.find()) {
propertyValues.add(pxMatcher.group());
}
谢谢你的快速回复。但它不适用于以下字符串。匹配器pxMatcher=pxPattern.matchermargin:0pt,6em,5%,2pt;