6

Lets say I have a string and it could be

1234

or

12 34

or

1 2 3 4 5

It doesn't matter about the number of digits or whitespace, just so that it accepts a string that has only digits and if there is whitespace within string of digits it will still accept it. How would I write the regex pattern for this?

3
  • What do you have so far? Commented Jan 28, 2014 at 1:20
  • Quick question for the OP (which I should have asked before posting an answer) - should the regexp match a string that consists only of whitespace? Or must there be at least one digit? Commented Jan 28, 2014 at 1:24
  • There should be atleast one digit within the string Commented Jan 28, 2014 at 1:25

2 Answers 2

10

Use String#matches() and a regex:

if (str.matches("[\\d\\s]+"))
    // string is acceptable
Sign up to request clarification or add additional context in comments.

Comments

2

If it's acceptable to have only whitespace, then the regexp you want is "[\\d\\s]+"

If there has to be one or more digits, then you could use "\\s*(\\d\\s*)+"

Note that I've doubled up the backslashes, assuming you're writing this in Java source, rather than reading it in from some other source of text. The actual regexp in the second case is \s*(\d\s*)+

3 Comments

Why is it that "1 2 3 4 5".matches("(\\d\\s)+") returns false (parens vs braces)? In other words, I thought I was saying the same thing, what am I really saying with my regex?
@tieTYT - that's a completely different question - but the short answer is that your regexp asks for one or more repetitions of one digit then one space. If you add a space to the end of your string, it will comply.
Oh dear, you're quite right, @ajb. I meant to ditch the square brackets. I'll edit it now. Thanks for the save.

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.