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

I have "222 22 222", "333 33 33 333", "123434", and "ab345 543"

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.

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.

Share Improve this question edited Sep 7, 2010 at 8:19 kennytm 524k110 gold badges1.1k silver badges1k bronze badges asked Sep 7, 2010 at 8:10 VicheanakVicheanak 6,70420 gold badges67 silver badges99 bronze badges 4
  • What language or tool are you using? Regular expressions have slightly different syntax in different languages. – Mark Byers Commented Sep 7, 2010 at 8:13
  • sorry. I used Javascript – Vicheanak Commented Sep 7, 2010 at 8:16
  • 1 What results would you expect for " " and "1234". ie All whitespaces and all numerics ? – El Ronnoco Commented Sep 7, 2010 at 8:33
  • i would expect it to return 222 22 222, 333 33 33 333 the same as I have input. But the third and the fourth won't return anything or return false. – Vicheanak Commented Sep 7, 2010 at 8:36
Add a ment  | 

3 Answers 3

Reset to default 7

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}]

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744905678a4600237.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信