【发布时间】:2012-01-06 03:58:11
【问题描述】:
很简单,如下所示的 idParser 没有在我的 passUrl 字符串中找到数字。 这是 Lod.d 的 LogCat:
01-05 11:27:48.532: D/WEBVIEW_REGEX(29447): Parsing: http://mymobisite.com/cat.php?id=33
01-05 11:27:48.532: D/WEBVIEW_REGEX(29447): idParse: No Matches Found.
annnnd 这里是麻烦的块。
Log.d("WEBVIEW_REGEX", "Parsing: "+passableUrl.toString());
Matcher idParser = Pattern.compile("[0-9]{5}|[0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1}").matcher(passableUrl);
if(idParser.groupCount() > 0)
Log.d("WEBVIEW_REGEX", "idParse: " + idParser.group());
else Log.d("WEBVIEW_REGEX", "idParse: No Matches Found.");
注意,我现在有点草率了,我尝试了一堆不同的语法(所有三种模式都在http://www.regextester.com/index2.html 验证过),我什至查看了文档(http://docs.oracle.com/javase/tutorial/essential/regex/char_classes.html) .这开始触动我最后的神经了。 使用
.find()
而不是 group() 的东西只会产生“假”......有人可以帮助我理解为什么我不能让这个正则表达式工作吗?
干杯!
【问题讨论】:
-
你的正则表达式真的很复杂...
\d{1,5}也有同样的效果! -
System.out.println(Pattern.compile("\\d{1,5}") .matcher("http://mymobisite.com/cat.php?id=33").find());--> 在这里打印true... -
@NiklasBaumstark 你可能指的是
.matches(),不幸的是Java 错误地命名了它的.matches()方法——它们试图匹配整个输入,这与正则表达式匹配的定义相矛盾 -
所以要重复重要的事情:为什么不直接使用
\d+?有长度限制还是只是不知道+的存在? -
好吧,即使是复杂的正则表达式(按原样复制/粘贴),这里的匹配器也会返回 true。你确定你使用
java.util.regex吗?