Skip to content
Advertisement

Regular expression – allow space and any number of digits

my valid string should be either "1234" or " 1234"

allow one or zero space at the beginning

then followed by any number of digits only

so what should be the regular expression for this ?

Advertisement

Answer

You can use this:

^ ?d+$

which is easier to read like this:

^[ ]?d+$

See demo.

To test if you have a match, you can do (for instance):

if (subjectString.matches("[ ]?\d+")) {
    // It matched!
    } 
else {  // nah, it didn't match...  } 

Here you don’t need the ^ and $ anchors, because the matches method looks for an exact match.

Explanation

  • The ^ anchor asserts that we are at the beginning of the string. Depending on the method used, these anchors may not be needed.
  • [ ]? matches zero or one space. The brackets are not needed, but they make it easier to read. You can remove them. Do not use s there as it also matches newlines and tabs.
  • d+ matches one or more digits
  • The $ anchor asserts that we are at the end of the string
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement