简体   繁体   中英

regular expression not matching for string

When I tried to use the below regular expression to get the values, it is not matching.

Pattern pattern = Pattern.compile("(\\d+),\\s(\\d+),\\s(\\d+),\\s(\\d+)");
Matcher matcher = pattern.matcher("(8,0), (0,-1), (7,-2), (1,1)");

while (matcher.find()) {
    int x = Integer.parseInt(matcher.group(1));
    int y = Integer.parseInt(matcher.group(2));
    System.out.printf("x=%d, y=%d\n", x, y);
}

Can anyone please tell me some solution for this ?

You can match (x,y) with \\\\((\\\\d+),(\\\\d+)\\\\) and if you also want to match negative values you can add - as an optional character. ie \\\\((-?\\\\d+),(-?\\\\d+)\\\\)

Pattern pattern = Pattern.compile("\\((-?\\d+),(-?\\d+)\\)");
Matcher matcher = pattern.matcher("(8,0),(0,-1),(7,-2),(1,1)");

while (matcher.find()) {
   int x = Integer.parseInt(matcher.group(1));
   int y = Integer.parseInt(matcher.group(2));
   System.out.printf("x=%d, y=%d\n", x, y);
}

OUTPUT

x=8, y=0
x=0, y=-1
x=7, y=-2
x=1, y=1

In \\\\((\\\\d+),(\\\\d+)\\\\) we have two groups of \\\\d+ which will match respective x and y coordinates and we have also escaped ( and ) to match brackets. For negative values we have added - as an optional character in both groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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