簡體   English   中英

正則表達式與字符串不匹配

[英]regular expression not matching for string

當我嘗試使用下面的正則表達式來獲取值時,它不匹配。

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

任何人都可以告訴我一些解決方案嗎?

您可以將(x,y)\\\\((\\\\d+),(\\\\d+)\\\\)匹配,如果您還想匹配負值,可以添加-作為可選字符。 \\\\((-?\\\\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);
}

輸出

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

\\\\((\\\\d+),(\\\\d+)\\\\)我們有兩組\\\\d+ ,它們將匹配各自的xy坐標,並且我們還轉義了()以匹配括號。 對於負值,我們添加了-作為兩個組中的可選字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM