[英]What's wrong with my regex -?\\d{2}\\.?\\d{6}
I'm trying extract lat and long from a url: 我正在尝试从url中提取lat和long:
source: ...sensor=false¢er=-15.842208999999999%2C-48.023084&zoom=17&size=256x256&language=en&client=google-maps-frontend&signature=hbey3U4lycTNgX48asW8MODjJLM
I'm not good in regexes, so I used this regex tester ( http://regexpal.com/ ) and coded this regex 我在正则表达式方面不是很好,所以我使用了这个正则表达式测试器( http://regexpal.com/ )并编写了这个正则表达式
-?\d{2}\.?\d{6}(is for JAVA ) (适用于JAVA)
It produces this result (who's saying it is regexpal.com): 它产生了这个结果(谁说它是regexpal.com):
for (Element element : newsHeadlines) {
if(element.toString().contains("https://maps.google.com")){
List<String> lista = get_matches(element.attr("content"), "-?\\d{2}\\.?\\d{6}");
}
}
public static List<String> get_matches(String s, String p) {
// returns all matches of p in s for first group in regular expression
List<String> matches = new ArrayList<String>();
Matcher m = Pattern.compile(p).matcher(s);
while(m.find()) {
matches.add(m.group(1)); //<-- Exception m.group(1) not have any results.
}
return matches;
}
So when I do it (in java): 所以当我这样做时(在java中):
for (Element element : newsHeadlines) { if(element.toString().contains("https://maps.google.com")){ List<String> lista = get_matches(element.attr("content"), "-?\\\\d{2}\\\\.?\\\\d{6}"); } } public static List<String> get_matches(String s, String p) { // returns all matches of p in s for first group in regular expression List<String> matches = new ArrayList<String>(); Matcher m = Pattern.compile(p).matcher(s); while(m.find()) { matches.add(m.group(1)); //<-- Exception m.group(1) not have any results. } return matches; }
What's wrong with my regex? 我的正则表达式有什么问题?
Your method get_matches
is looking for m.group(1)
groups are defined in Regex with Parenthesis. 你的方法get_matches
正在寻找m.group(1)
组在Regex中使用括号定义。 So you regex needs to be like this instead: 所以你的正则表达式需要像这样:
(-?\\d{2}\\.?\\d{6})
Just make one symbol as optional whether it may be -
or .
只需将一个符号作为可选符号,无论是否为-
或.
. 。
-\d{2}\.?\d{6}
Equivalent java regex: 等价的java正则表达式:
-\\d{2}\\.?\\d{6}
OR 要么
-?\d{2}\.\d{6}
Equivalent java regex: 等价的java正则表达式:
-?\\d{2}\\.\\d{6}
And call m.group(0)
to print only the matched strings. 并调用m.group(0)
仅打印匹配的字符串。 If you want to call m.group(1)
then you need to enclose the patterns within paranthesis. 如果要调用m.group(1)
则需要将模式括在paranthesis中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.