String str = "POLYGON((39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824))";
我试图只获得39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824
同
final String coordsOnly = str.replaceAll("\\D\\(\\(\\w\\)\\)", "$2");
但我得到coordsOnly = "POLYGON((39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824))"
我错过了什么?
这里一个合理的方法是匹配以下模式,然后用第一个捕获组替换all:
POLYGON\(\((.*?)\)\)
示例代码:
final String coordsOnly = str.replaceAll("POLYGON\\(\\((.*?)\\)\\)", "$1");
编辑:
如果你还需要隔离数字对,你可以在逗号上使用String#split()
。实际上,这看起来像数据库查询的输出,我怀疑数据库可能提供更好的方法来获取单个值。但是,如果您无法获得所需的确切输出,这里给出的答案是一个选项。
实际上,很多。
"\\D" // Matches a non-digit character, but it only matches one,
// while you need to match a word "POLYGON";
"\\(\\(" // Good. Matches the double left parentheses ((
"\\w" // One word character? Same issue, you need to match multiple chars. And what about '.'?
"\\)\\)" // Good. Matches the double right parentheses ))
逃脱的()
没有创建匹配组;和\\w
只匹配一个单词字符[a-zA-Z_0-9]
,它甚至不匹配.
。
我相信你应该尝试这样的事情:
String coords = str.replaceAll("POLYGON\\(\\(([^)]+)\\)\\)", "$1");
也许这就是你想要的?:
String rex = "[+-]?([0-9]*[.])?[0-9]+";
Pattern p = Pattern.compile(rex);
String input = "POLYGON((39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824))";
Matcher matcher = p.matcher(input);
while(matcher.find()) {
System.out.println(matcher.group());
}
试试这个版本:
str = str.replaceAll("[^\\d\\.\\s,]", "");
String str = "POLYGON((39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824))";
String sp = "(([0-9]+[.])?[0-9]+[,]?\\s*)+";
Pattern p = Pattern.compile(sp);
Matcher matcher = p.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group());
}
输出:
39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824
另一种选择是替换所有非数字,空格,点或逗号:
str.replaceAll("[\\D&&\\S&&[^,\\.]]", "")
输出:
39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824