我有这个字符串:
<meis xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" uri="localhost/naro-nei" onded="flpSW531213" identi="lemenia" id="75" lastStop="bendi" xsi:noNamespaceSchemaLocation="http://localhost/xsd/postat.xsd xsd/postat.xsd">
如何在JAVA中获取lastStop
属性值?
这个正则表达式在http://www.myregexp.com/上测试成功。
但是当我在Java中尝试时,我没有看到匹配的文本,以下是我的尝试:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SimpleRegexTest {
public static void main(String[] args) {
String sampleText = "<meis xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" uri=\"localhost/naro-nei\" onded=\"flpSW531213\" identi=\"lemenia\" id=\"75\" lastStop=\"bendi\" xsi:noNamespaceSchemaLocation=\"http://localhost/xsd/postat.xsd xsd/postat.xsd\">";
String sampleRegex = "(?<=lastStop=[\"']?)[^\"']*";
Pattern p = Pattern.compile(sampleRegex);
Matcher m = p.matcher(sampleText);
if (m.find()) {
String matchedText = m.group();
System.out.println("matched [" + matchedText + "]");
} else {
System.out.println("didn’t match");
}
}
}
也许问题在于我在测试中使用了转义字符,但实际字符串内部没有转义。 更新 有人知道为什么在Java中使用时这不起作用吗?或者如何使其起作用?
?
(字符组后面的那个)。由于输入似乎是 XML,引号无论如何都不是可选项,因此删除它不是问题,并且可以使正则表达式起作用。 - Joachim Sauer