簡體   English   中英

如何檢查正則表達式中輸入的只有數字和空格?

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

我有“ 222 22 222”,“ 333 33 33 333”,“ 1234/34”和“ ab345 543”,我想檢查這些輸入是否為數字和空格。 在這種情況下,第一個和第二個輸入應使用正則表達式測試方法返回True,或者使用Exec方法返回其自己的值。 第三和第四應該返回false。 我該如何在正則表達式中這樣做? 請幫忙。 謝謝。

您可以使用以下正則表達式進行測試:

/^[\d\s]+$/

紅寶石


如果還要檢查字符串中至少有一位數字:

/^\s*\d[\d\s]*$/

您可以使用如下正則表達式:^(?:[0-9] | \\ s)* $

這是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())

結果是:

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

干杯安德里亞

我認為應該是[\\ d \\ s {0,1}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM