繁体   English   中英

使用编码的双引号解析简单属性

[英]simple attribute parsing with encoded double-quotes

我正在使用Regex解析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的地图。值应该是带有双引号的文本\\“这里

您可以使用交替和正面的lookbehind断言

Pattern attributePattern = Pattern.compile("[a-z0-9]*=\"(?:[^\"]*|(?<=\\\\)\")*\"");

(?:[^\\"]*|(?<=\\\\\\\\)\\")*是一个替代,匹配[^\\"]*(?<=\\\\\\\\)\\"

(?<=\\\\\\\\)\\"匹配一个”,但(?<=\\\\\\\\)\\"是它有一个反冲。

你可以使用负面看后面来查看引用前是否有反斜杠,但如果反斜杠本身也可以转义,则会失败:

myAttribute="some text with a trailing backslash \\"

如果可以,尝试这样的事情:

Pattern.compile("[a-zA-Z0-9]+=\"([^\"\\\\]|\\\\[\"\\\\])*\"")

快速解释:

[a-zA-Z0-9]+     # the key
=                # a literal '='
\"               # a literal '"'
(                # start group
  [^\"\\\\]      #   any char except '\' and '"'
  |              #   OR
  \\\\[\"\\\\]   # either '\\' or '\"'
)*               # end group and repeat zero or more times
\"               # a literal '"'

快速演示:

public class Main {

    private static HashMap<String, String> findAttributes(Pattern p, String macroAttributes) {
        Matcher matcher = p.matcher(macroAttributes);
        HashMap<String, String> map = new HashMap<String, String>();
        while (matcher.find()) {
            map.put(matcher.group(1), matcher.group(2));
        }
        return map;
    }

    public static void main(String[] args) {
        final String text = "my=\"some text with a double quote \\\" here\"";
        System.out.println(findAttributes(Pattern.compile("([a-z0-9]+)=\"((?:[^\"\\\\]|\\\\[\"\\\\])*)\""), text));
        System.out.println(findAttributes(Pattern.compile("([a-z0-9]*)=\"((?:[^\"]*|(?<=\\\\)\")*)\""), text));
    }
}

将打印:

{my=some text with a double quote \" here}
{my=some text with a double quote \}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM