這在支持模式匹配的函式式語言中很常見,所以我的直覺希望這是可能的。
我正在尋找類似的東西:
match string:
case "[a-zA-Z]":
... do something
case _:
print("Not a match")
即使沒有直接的方法來做到這一點,是否有任何合理的語法來實作相同的目標?
uj5u.com熱心網友回復:
這意味著您在兩個地方都有可能的模式……但這與我目前所能想到的問題的精神最接近。
import re
test = 'hello'
patterns = ['(h)', '(e)', '(ll)', '(ello)']
for pattern in patterns:
matches = re.search(pattern, test)
if matches:
match pattern:
case '(h)':
print('matched (h)')
# break # add a break after each case if you want to stop after a match is found.
case '(e)':
print('matched (e)')
...etc
uj5u.com熱心網友回復:
Python的re模塊做正則運算式,所以你可以使用if-elif-else:
import re
string = "test_string"
if re.match("[a-zA-Z]", string):
# string starts with a letter
elif re.match("[0-9]", string):
# string starts with a digit
else:
# string starts with something else
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457094.html
標籤:Python 正则表达式 模式匹配 python-3.10
