tags:

views:

52

answers:

3

I'm trying the following segment to no avail:

 public class test {

    public static void main(String args[] ){

       String password = "s8bgBQYPmUaNjkToXCJLAwAA";
       System.out.println( Pattern.matches("[0-9]", password ));

   }

}

I would expect that to work since I'm just looking for match of any digit to suffice the regex but my output always comes back false. Any help as to what I maybe missing or what could be wrong would be most appreciated.

+2  A: 

You're checking whether the whole string consists of one single digit. What you really mean is:

System.out.println( Pattern.matches(".*[0-9].*", password ));

Adding the .* to the start and end lets it match any number of other characters (. means "any character" and * means "any number of times").

Michael Myers
A: 

you may or may not want to use [A-z] instead of . if you don't want it to match special characters. I'm not a java guy, so the specifics of regex in java are best presented by: http://www.regular-expressions.info/java.html

netricate
Did you really mean to write `[A-z]` (capital `A`, lowercase `z`)? That's almost certainly an error, no matter what regex flavor you're working with. And who are you talking to, anyway? I suspect this should have been posted as a comment on @mmyers' answer, not as an answer in its own right.
Alan Moore
agreed, apologies for not just commenting. Yes, i mean to cap the Z.
netricate
A: 

If you're doing this type of character interrogation often in a loop, you may not want to use a regexp at all but craft your own search routine interrogating a StringBuffer.

/**
* Method to evaluate a String to see whether it contains one (or potentially more) of a 
* char or member of a group of chars.
*
* @param String to evaluate
*
* @param String containing all characters to evaluate against the subject string
*
* @return true on first correct match, false if no match found
**/

public boolean sbContainsOneOf(String sStringToCheck, String sCheck)
{
StringBuffer sb = new StringBuffer(sStringToCheck);

char[] tmp2 = sCheck.toCharArray();

for (int i = 0; i < sb.length(); i++)
    {

    for (int k = 0; k < tmp2.length; k++)
    if (sb.charAt(i) == tmp2[k])
        {
            return true;
        }

    }
return false;
}

Then all you need to do is call it:

String password = "s8bgBQYPmUaNjkToXCJLAwAA"; 
System.out.println(sbContainsOneOf(password,"0123456789"));

It's between 10 and 15 times faster doing it this way.... The longer your String & option list the bigger the difference between the two becomes. Generally I avoid regexps unless they're one offs or spectacularly complex to implement as code and prefer to rep them with optimised StringBuffer-based routines. Doing it this way, gradually your collection of regexp replacements fills up and you end up with a very useable way of pattern interrogation without the high associated regexp overheads.

Szyzygy