2

I wanted to test if a string contains numbers (at least one number) so I tried out this:

public class Test {
private static final String DIGIT_PATTERN = "^(?=.*\\d)";
private static final Pattern DIGIT_PATTERN_COMPILED = Pattern.compile(DIGIT_PATTERN);

/**
 * 
 * @param args
 */
public static void main(String[] args) {
    String passwordOne = "123";
    String passwordTwo = "abc";

    Matcher matcher = null;

    matcher = DIGIT_PATTERN_COMPILED.matcher(passwordOne);

    if(!matcher.matches()) {
        System.out.println("Password " + passwordOne + " contains no number");
    } else {
        System.out.println("Password " + passwordOne + " contains number");
    }

    matcher = DIGIT_PATTERN_COMPILED.matcher(passwordTwo);

    if(!matcher.matches()) {
        System.out.println("Password " + passwordTwo + " contains no number");
    } else {
        System.out.println("Password " + passwordTwo + " contains number");
    }   
}
}

Unfortunately both if clauses print out that it contains no number. Am I using the regex wrong?

2
  • 1
    Please tag your question with the language (java?). Commented Nov 20, 2013 at 9:46
  • What is a digital number, BTW? Commented Nov 20, 2013 at 9:57

3 Answers 3

3

The most basic pattern

".*[0-9].*"

works for me with your code.

Sign up to request clarification or add additional context in comments.

2 Comments

this worked for me. the \\d did not work for me
Glad to hear it!
2

Just try with following regex:

private static final String DIGIT_PATTERN = "\\d+";

4 Comments

i fount this rege: ^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\S+$).{8,}$ and thought it is possible to just splitt it up
There is no need to involve this bunch of regex if you just want to check if is there \\d.
i want to check the whole regex but step by step do print out different messages when something is missing in my password. so i thought simply splitting it up would do the trick.
System.out.println("200SSS".matches("\\d+")); returns false because it only looks for digits in the string, so using System.out.println("200SSS".matches(".*[0-9].*")); yields true to me because I am looking for atleast one digit in a string
1

Why not just use

private static final String DIGIT_PATTERN = "\\d";

That should match if there's any number in there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.