我正在用正则表达式解析Java中的一些文本
我有看起来像这样的字符串:myAttribute =“ some text”,并像这样解析它们
Pattern attributePattern = Pattern.compile("[a-z0-9]*=\"[^\"]*\"");
但是,我意识到人们可能希望在其属性值中使用双引号。
例如myAttribute =“一些带有双引号\”的文本在这里“
我如何调整我的正则表达式来处理此问题
这是我解析属性的代码
private HashMap<String, String> findAttributes(String macroAttributes) {
Matcher matcher = attributePattern.matcher(macroAttributes);
HashMap<String, String> map = new HashMap<String, String>();
while (matcher.find()) {
String attribute = macroAttributes.substring(matcher.start(), matcher.end());
int equalsIndex = attribute.indexOf("=");
String attrName = attribute.substring(0, equalsIndex);
String attrValue = attribute.substring(equalsIndex+2, attribute.length()-1);
map.put(attrName, attrValue);
}
return map;
}
findAttributes("my=\"some text with a double quote \\\" here\"");
应该返回大小为1的地图
值应该是一些带有双引号\“的文本
最佳答案
您可以为此使用交替和肯定的后向断言
Pattern attributePattern = Pattern.compile("[a-z0-9]*=\"(?:[^\"]*|(?<=\\\\)\")*\"");
(?:[^\"]*|(?<=\\\\)\")*
是替代,匹配[^\"]*
或(?<=\\\\)\"
(?<=\\\\)\"
匹配“”,但前提是它后面带有反冲。关于java - 具有编码双引号的简单属性解析,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15198872/