java - Regular expression - allow space and any number of digits -


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

allow one or 0 space @ beginning

then followed number of digits only

so should regular expression ?

you can use this:

^ ?\d+$ 

which easier read this:

^[ ]?\d+$ 

see demo.

to test if have match, can (for instance):

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

here don't need ^ , $ anchors, because matches method looks exact match.

explanation

  • the ^ anchor asserts @ beginning of string. depending on method used, these anchors may not needed.
  • [ ]? matches 0 or 1 space. brackets not needed, make easier read. can remove them. do not use \s there matches newlines , tabs.
  • \d+ matches 1 or more digits
  • the $ anchor asserts @ end of string

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -