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.
views:
51answers:
3
+7
A:
You can test with this regular expression:
/^[\d\s]+$/
If you want to also check that there is at least one digit in the string:
/^\s*\d[\d\s]*$/
Mark Byers
2010-09-07 08:13:15
^[\d\s]+$ (since i think he does not want to match empty string)
dweeves
2010-09-07 08:16:10
+1 for the Rubular test link
Johnsyweb
2010-09-07 08:19:33
@dweeves: Yes, you are probably right. I've updated the answer.
Mark Byers
2010-09-07 08:24:27
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
2010-09-07 08:30:18
Thank you very much
Vicheanak
2010-09-07 08:42:33
I added an alternative answer that ensures at least one digit.
Mark Byers
2010-09-07 09:14:19
+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
2010-09-07 08:17:25