0

我需要一些帮助来创建一个正则表达式(在 java 中)来找到一个像这样的模式:

(30.6284, -27.3493)

它大致是一个纬度经度对。从较小的部分构建,我想出了这个:

String def = "\\((\\-?\\d+\\.\\d+),\\s*(\\-?\\d+\\.\\d+)\\)";

如果括号之前或之后没有任何字符,这可以正常工作。所以这失败了:

"hello (30.6284, -27.3493)   "

但如果我删除之前的“hello”和尾随空格,它会起作用。如何忽略表达式前后的任何其他字符序列?

谢谢

4

3 回答 3

0
String s = "hello (30.6284, -27.3493)   ";
System.out.println(s.replaceAll(".*(\\((\\-?\\d+\\.\\d+),\\s*(\\-?\\d+\\.\\d+)\\)).*","$1"));

输出:(30.6284,-27.3493)

请注意,如果您要循环查找内容,我会使用以下内容:

Matcher m = Pattern.compile(".*(\\((\\-?\\d+\\.\\d+),\\s*(\\-?\\d+\\.\\d+)\\)).*").matcher(s);
while(m.find()){
    System.out.println(m.start()+ " " + m.group(1));
}
于 2013-06-15T05:31:53.060 回答
0

我想出了这个使用这个网站:http ://regexpal.com/和http://www.regextester.com/

\(-?\d+\.?\d+, -?\d+\.?\d+\)

This will match, but not capture, and probably isn't in your language specific format (but should be easily modifiable. To support capturing you could use this one:

\((-?\d+\.?\d+), (-?\d+\.?\d+)\)
于 2013-06-15T05:31:59.730 回答
0

You can use the following piece of code to find and extract multiple instances of the pattern in your text.

    String def = "\\((\\-?\\d+\\.\\d+),\\s*(\\-?\\d+\\.\\d+)\\)";
    String text = "hello (30.6284, -27.3493)  (30.6284, -27.3493) ";
    Pattern p = Pattern.compile(def);
    Matcher m = p.matcher(text);
    while (m.find()) {
        System.out.println(text.substring(m.start(), m.end()));
    }
于 2013-06-15T06:01:25.173 回答