我想知道測驗命名捕獲組是否存在的正確方法。具體來說,我有一個將編譯的正則運算式作為引數的函式。正則運算式可能有也可能沒有特定的命名組,命名組可能存在也可能不存在于傳入的字串中:
some_regex = re.compile("^foo(?P<idx>[0-9]*)?$")
other_regex = re.compile("^bar$")
def some_func(regex, string):
m=regex.match(regex,string)
if m.group("idx"): # get *** IndexError: no such group here...
print(f"index found and is {m.group('idx')}")
print(f"no index found")
some_func(other_regex,"bar")
我想在不使用的情況下測驗該組是否存在try——因為這會使函式的其余部分短路,如果找不到命名的組,我仍然需要運行該函式
uj5u.com熱心網友回復:
您可以使用Pattern.groupindex檢查組名是否存在:
def some_func(regex, group_name):
return group_name in regex.groupindex
檔案說:
Pattern.groupindex
將定義的任何符號組名稱映射(?P<id>)到組編號的字典。如果模式中沒有使用符號組,則字典為空。
請參閱Python 演示:
import re
some_regex = re.compile("^foo(?P<idx>[0-9]*)?$")
other_regex = re.compile("^bar$")
def some_func(regex, group_name):
return group_name in regex.groupindex
print(some_func(some_regex,"bar")) # => False
print(some_func(some_regex,"idx")) # => True
print(some_func(other_regex,"bar")) # => False
print(some_func(other_regex,"idx")) # => False
uj5u.com熱心網友回復:
您可以檢查物件groupdict的match:
import re
some_regex = re.compile("^foo(?P<idx>[0-9]*)?$")
match = some_regex.match('foo11')
print(True) if match and 'idx' in match.groupdict() else print(False) # True
match = some_regex.match('bar11')
print(True) if match and 'idx' in match.groupdict() else print(False) # False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/435006.html
