我有一個看起來像這樣的正則運算式:
bool(re.match('^(0|[.]{0,1}[1-9][.]{0,1}[0-9]*)$', "0.123"))
這很完美,但是當包含如上例所示的小數時,它與前導零不匹配。我的目標是只匹配包含小數的前導零數字。不應匹配諸如“01”之類的字串。可以匹配十進制數或整數。
我將如何創建與此匹配的正則運算式?
一些場景:
0.01 Match
1 Match
1.2 Match
.01 Match
-0.1 Match
-1 Match
1.2.3 No Match
01 No Match
001.1 No Match
00.1 No Match
uj5u.com熱心網友回復:
這是一種非正則運算式方法,看起來像通過了所有提到的測驗用例:
numbers = """\
0.123
0
01
0.01
1
1.2
.01
-0.1
-1
1.2.3
-01.2
01
-01
001.1
00.1\
"""
def is_valid_num(s: str):
unsigned_s = s.lstrip('- ')
if unsigned_s.startswith('0'):
try:
if not unsigned_s[1] == '.':
return False
except IndexError:
# It's just a zero (0)
return True
try:
_ = float(s)
return True
except ValueError:
return False
if __name__ == '__main__':
for n in numbers.split('\n'):
print(f'{n:<10} -> {is_valid_num(n)!r:>10}')
輸出:
0.123 -> True
0 -> True
01 -> False
0.01 -> True
1 -> True
1.2 -> True
.01 -> True
-0.1 -> True
-1 -> True
1.2.3 -> False
-01.2 -> False
01 -> False
-01 -> False
001.1 -> False
00.1 -> False
uj5u.com熱心網友回復:
在您的示例中,您可以使用此正則運算式:
^-?(((?!0)[0-9] |0)(\.[0-9] )?|\.[0-9] )$
我不確定這2.是否是一個數字。如果是,您可以使用:
^-?(((?!0)[0-9] |0)(\.([0-9] )?)?|\.[0-9] )$
uj5u.com熱心網友回復:
使用任何適用的擴展測驗并使用或調整這個簡單的 re:
In [1]: tests_map = {True: ['0.01', '1', '1.2', '.01', '01'],
...: False: ['1.2.3']}
In [2]: pattern = r'^\d*\.{0,1}\d*$'
In [3]: import re
In [4]: for result, tests in tests_map.items():
...: for test in tests:
...: if not (bool(re.match(pattern, test)) == result):
...: print(f"{test} was not {result}")
...:
您可以將模式“讀”為“零個或多個十進制字符后跟零或一個小數點后跟零個或多個十進制字符”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/323638.html
上一篇:Unity3d C# UGUI實作一個自動回圈滾動的串列(ScrollRect)的功能(含工程原始碼)
下一篇:正則運算式匹配字串中的奇數
