views:

51

answers:

3

I have "222 22 222", "333 33 33 333", "1234/34", and "ab345 543" and I want to check whether these inputs are numeric and white space. I.E this case, the first and the second inputs should return True by using method Test of Regular Expression, or return its own value by using Exec method. The third and the fourth should return false. How could I do so in Regular Expression? Please help. Thank you.

+7  A: 

You can test with this regular expression:

/^[\d\s]+$/

Rubular


If you want to also check that there is at least one digit in the string:

/^\s*\d[\d\s]*$/
Mark Byers
^[\d\s]+$ (since i think he does not want to match empty string)
dweeves
+1 for the Rubular test link
Johnsyweb
@dweeves: Yes, you are probably right. I've updated the answer.
Mark Byers
Does the OP also want to ensure there are some numerics or are they happy to match an entirely whitespace string? They aren't clear.
El Ronnoco
Thank you very much
Vicheanak
I added an alternative answer that ensures at least one digit.
Mark Byers
A: 

I think it should be something like [\d\s{0,1}]

Raj
This will not match repeated characters
El Ronnoco
+1  A: 

You can use something like this regex: ^(?:[0-9]|\s)*$

Here's a test case in python:

test=["222 22 222", "333 33 33 333", "1234/34","ab345 543"]
for i in test:
    m = re.match("^(?:[0-9]|\s)*$", i)
    if (m == None): print("False")
    else: print("True: %s" % m.group())

The resut is:

True: 222 22 222
True: 333 33 33 333
False
False

Cheers Andrea

nivox