quarks
quarks

Reputation: 35276

Escape regex String in Java

What is the proper way to escape this String 0x\w+:0x\w+[^][]*\K\[(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)\] to be used as a Java String variable.

IntelliJ escapes this automatically into (when pasted):

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

However, this is causing compiler error:

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

Upvotes: 0

Views: 476

Answers (2)

quarks
quarks

Reputation: 35276

Here's what worked for me:

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

And here's the complete code (a bit long solution):

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);
    }
}

Upvotes: 0

Jade
Jade

Reputation: 455

\K is not valid regex. Not sure what you are trying to match with it. If you want a capitol K character, just put K

Upvotes: 1

Related Questions