简体   繁体   中英

Java Regular Expression Not Finding My Char Class

Very simply, idParser as seen below is not finding the number in my passedUrl string. Here is the LogCat out for the Lod.d's:

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.

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 ). 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?

Cheers!

The problem is that groupCount() doesn't do what you think it does. You should instead use 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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