简体   繁体   English

Java正则表达式找不到我的Char类

[英]Java Regular Expression Not Finding My Char Class

Very simply, idParser as seen below is not finding the number in my passedUrl string. 很简单,如下所示,idParser没有在我的passUrl字符串中找到数字。 Here is the LogCat out for the Lod.d's: 这是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 heres the block of trouble. annnnd heres the block of trouble。

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.");

note, this is me getting a bit sloppy now, I've tried a bunch of different syntaxes (all verified working at http://www.regextester.com/index2.html on all three modes ) and I've even looked up the documentation ( http://docs.oracle.com/javase/tutorial/essential/regex/char_classes.html ). 请注意,这是我现在有点草率,我尝试了一堆不同的语法(所有三种模式都验证了http://www.regextester.com/index2.html )我甚至查了一下文档( http://docs.oracle.com/javase/tutorial/essential/regex/char_classes.html )。 This is starting to get on my final nerve. 这开始变得我最后的神经。 using 运用

.find()

instead of group() stuff just yields "false" ... Can someone help me to understand why i cant get this regular expression to work? 而不是group()的东西只会产生“假”...有人可以帮助我理解为什么我不能让这个正则表达式工作?

Cheers! 干杯!

The problem is that groupCount() doesn't do what you think it does. 问题是groupCount()没有做你认为它做的事情。 You should instead use idParser.find() . 您应该使用idParser.find() Like this: 像这样:

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

You could also simplify the pattern a bit, using \\d{1,5} instead: 您也可以使用\\d{1,5}来简化模式:

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

Full example: 完整示例:

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.");

Outputs: 输出:

idParse: 33

There are no ( ) braces hence zero groups. 没有( )括号因此为零组。

All groups are numbered from left to right with a starting ( . Matcher.group(1) would be the first group. Matcher.group() is the entire match. You need find() to move to the first match. Others already indicated there are simpler patterns, like "\\\\d+$" , a string ending with at least one digit. 所有组都是从左到右编号的一个起点( .Matcher.group(1)将是第一组.Matcher.group()是整个匹配。你需要find()移动到第一场比赛。其他已经指示有更简单的模式,比如"\\\\d+$" ,一个以至少一个数字结尾的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM