SS44
SS44

Reputation: 847

Java Regex Match Error

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.

Upvotes: 2

Views: 1668

Answers (3)

Szyzygy
Szyzygy

Reputation: 106

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.

Upvotes: 0

netricate
netricate

Reputation: 1728

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

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 191865

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

Upvotes: 2

Related Questions