Karibasappa G C
Karibasappa G C

Reputation: 2732

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 ?

Upvotes: 1

Views: 8039

Answers (5)

alps_ren
alps_ren

Reputation: 11

try this: "[\\d\\s]+"

Upvotes: 0

Federico Piazza
Federico Piazza

Reputation: 30995

If your input data must be only one space (not a whitespace), so the regex you need is ?\d+ (Note the space before "?").

On the other hand, if your input data must contain a whitespace, so you need to tweak the regex to:

\s?\d+

A whitespace character can be:

A space character
A tab character
A carriage return character
A new line character
A vertical tab character
A form feed character

As a note, if you need to discard all any character after your digits, for instace 1234fff doesn't have to be matched, then you can fix your regex to: \s?\d+\b (this will make your regex to have a boundary).

Remember to escape backslashes in java code, so \s?\d+ will be \\s?\\d+

Below you can find the regex for one space followed by only digits.

enter image description here

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174706

Your regex would be,

^\s?[0-9]+$

Demo

Explanation:

  • ^ Asserts that we are at the begining of the line.
  • \s? A zero or one space is allowed.
  • [0-9]+ One or more numbers.
  • $ Asserts that we are at the end of the line.

Upvotes: 2

zx81
zx81

Reputation: 41838

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

Upvotes: 4

M A
M A

Reputation: 72854

It should be \\s?\\d+

System.out.println(Pattern.matches("\\s?\\d+", "1234"));  // true
System.out.println(Pattern.matches("\\s?\\d+", " 1234"));  // true
System.out.println(Pattern.matches("\\s?\\d+", "  1234"));  // false

\s denotes whitespaces and the ? means zero or one occurence. The \d corresponds to a digit with + meaning at least one occurence.

In case only the space character is allowed (e.g. no tabs), use ( )?\\d+

Upvotes: 3

Related Questions