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

夙愿已清 提交于 2020-01-05 04:32:05

问题


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.


回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/3656869/how-can-i-check-the-input-is-only-number-and-white-space-in-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!