开发者

how can I check the input is only number and white space in regular expression?

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.


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]*$/


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜