【问题标题】:Java Regular Expression Not Finding My Char ClassJava 正则表达式找不到我的 Char 类
【发布时间】: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吗?

标签: java android regex


【解决方案1】:

问题是groupCount() 并没有按照你的想法去做。您应该改用idParser.find()。像这样:

if(idParser.find())
    Log.d("WEBVIEW_REGEX", "idParse: " + idParser.group());
else Log.d("WEBVIEW_REGEX", "idParse: No Matches Found.");

您也可以稍微简化一下模式,改用\d{1,5}

Matcher idParser = Pattern.compile("\\d{1,5}").matcher(passableUrl);

完整示例:

String passableUrl = "http://mymobisite.com/cat.php?id=33";
Matcher idParser = Pattern.compile("\\d{1,5}").matcher(passableUrl);
if (idParser.find())
    System.out.println("idParse: " + idParser.group());
else 
    System.out.println("idParse: No Matches Found.");

输出:

idParse: 33

【讨论】:

  • 引用问题:.find() ... 只是产生“假”。
  • 这最终奏效了。最后,我确实只是像示例中那样将正则表达式换成("\\d{1,5}"),然后事情就开始正常了。我仍然很好奇为什么我以前没有工作过其他正则表达式(像"[0-9]{1,5}" 这样的东西完全没有产生任何结果),就像我说的,我总是用 regextester v2 检查我的正则表达式。
【解决方案2】:

没有( ) 大括号,因此是零组。

所有组从左到右编号,以( 开头。 Matcher.group(1) 将是第一组。 Matcher.group() 是整个匹配。您需要find() 才能移动到第一场比赛。其他人已经指出有更简单的模式,例如"\\d+$",一个至少以一位数字结尾的字符串。

【讨论】:

  • 是的,这是问题的一部分,但随后 OP 说匹配器上的 .find() 返回 false ——这违反了逻辑
  • @fge 该模式有效(在 Java 7 中)。有那么一刻,我想知道他是否还有其他竖线符号,或者会比 char 类序列更紧密地绑定 |"\d\d\d\d(\d|\d)\d\d(\d|\d)\d\(\d|\d)" = 10 位。
猜你喜欢
  • 1970-01-01
  • 2016-09-28
  • 2012-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
相关资源
最近更新 更多