在Java中转义正则表达式字符串

时间:2018-03-31 16:48:36

标签: java regex

将此String 0x\w+:0x\w+[^][]*\K\[(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)\]转义为Java String变量的正确方法是什么。

IntelliJ 自动将其转义为(粘贴时):

String pattern = "0x\\w+:0x\\w+[^][]*\\K\\[(\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?)\\]";

但是,这会导致编译器错误:

java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 18

2 个答案:

答案 0 :(得分:1)

\K无效正则表达式。不确定你想要匹配它。如果你想要一个国会大厦K字符,只需要K

答案 1 :(得分:0)

这对我有用:

\[\["0x\w+:0x\w+(.+?[\d+,\d+]]])

这是完整的代码(有点长的解决方案):

String arrayPatternString = "\\[\\[\"0x\\w+:0x\\w+(.+?[\\d+,\\d+]]])";
Pattern arrayPattern = Pattern.compile(arrayPatternString);
Matcher arrayMatcher = arrayPattern.matcher(responseBody);
while(arrayMatcher.find()) {
    String matched = arrayMatcher.group();
    String g = "(\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?)";
    Pattern gPattern = Pattern.compile(g);
    Matcher gMatcher = gPattern.matcher(matched);
    while(gMatcher.find()) {
        String gMatched = gMatcher.group();
        String[] s = gMatched.split(",");
        Double lat = Double.valueOf(s[0]);
        Double lon = Double.valueOf(s[1]);
        System.out.println("Lat: " + lat);
        System.out.println("Lat: " + lon);
        map.put("latitude", lat);
        map.put("longitude", lon);
    }
}