Regex 尝试在python中将字符串与多个模式匹配
我正在尝试下面的python代码,但出现了一个错误。我想要的是,如果target_分支匹配testrel变量中的任何模式,那么它应该说是。目标分支的值可能是release/1.0.0或r11\u i12格式,因此如果它与任何模式匹配,则说是,否则什么也不说。可以像下面这样定义多个模式吗Regex 尝试在python中将字符串与多个模式匹配,regex,python-2.7,Regex,Python 2.7,我正在尝试下面的python代码,但出现了一个错误。我想要的是,如果target_分支匹配testrel变量中的任何模式,那么它应该说是。目标分支的值可能是release/1.0.0或r11\u i12格式,因此如果它与任何模式匹配,则说是,否则什么也不说。可以像下面这样定义多个模式吗 import re testrel = ['r(\d+)_(i\d+)', 'release/\d+.\d+.\d+'] target_branch = "r11_i12" if re.match(testr
import re
testrel = ['r(\d+)_(i\d+)', 'release/\d+.\d+.\d+']
target_branch = "r11_i12"
if re.match(testrel, target_branch):
print 'Yes'
错误:
Traceback (most recent call last):
File "test.py", line 8, in <module>
if re.match(testrel, target_branch):
File "C:\Python27\Lib\re.py", line 137, in match
return _compile(pattern, flags).match(string)
File "C:\Python27\Lib\re.py", line 229, in _compile
p = _cache.get(cachekey)
TypeError: unhashable type: 'list'
回溯(最近一次呼叫最后一次):
文件“test.py”,第8行,在
如果重新匹配(testrel,target_分支):
文件“C:\Python27\Lib\re.py”,第137行,匹配
返回编译(模式、标志)。匹配(字符串)
文件“C:\Python27\Lib\re.py”,第229行,在编译中
p=\u cache.get(cachekey)
TypeError:不可损坏的类型:“列表”
看看这是否适合您:
import re
testrel = r'^r[\w+\/.]*'
target_branch = ["r11_i12",
"release/1.0.0",
"release/4.8.0",
"r11_i13",]
for x in target_branch:
if re.match(testrel, x):
print('Yes', end = '; ')
# Output:
## Yes; Yes; Yes; Yes;
注意:这是对您的要求的狭义回答。如果你想更具体的话,考虑另一种模式来避免不必要的匹配。 看看这是否适用于你:
import re
testrel = r'^r[\w+\/.]*'
target_branch = ["r11_i12",
"release/1.0.0",
"release/4.8.0",
"r11_i13",]
for x in target_branch:
if re.match(testrel, x):
print('Yes', end = '; ')
# Output:
## Yes; Yes; Yes; Yes;
注意:这是对您的要求的狭义回答。如果你想更具体的话,考虑另一种模式来避免不必要的匹配。 < P>第一个参数是一个模式,你试图通过一个列表。
您可以使用一个正则表达式,使用一个或另一个匹配的正则表达式
(?:r\d+_i\d+|release/\d+\.\d+\.\d+)$
re.match在字符串的开头开始匹配,这样您就不需要^
锚定,但您可以添加锚定$
来断言字符串的结尾,例如release/4.8.0 text
不是匹配
注意:转义点\。
以逐字匹配
|
例如:
import re
testrel = r"(?:r\d+_i\d+|release/\d+\.\d+\.\d+)$"
target_branches = ["r11_i12", "release/4.8.0"]
for target_branch in target_branches:
if re.match(testrel, target_branch):
print 'Yes'
的第一个参数是一个模式,您正在尝试传递一个列表
您可以使用一个正则表达式,使用一个或另一个匹配的正则表达式
(?:r\d+_i\d+|release/\d+\.\d+\.\d+)$
re.match在字符串的开头开始匹配,这样您就不需要^
锚定,但您可以添加锚定$
来断言字符串的结尾,例如release/4.8.0 text
不是匹配
注意:转义点\。
以逐字匹配
|
例如:
import re
testrel = r"(?:r\d+_i\d+|release/\d+\.\d+\.\d+)$"
target_branches = ["r11_i12", "release/4.8.0"]
for target_branch in target_branches:
if re.match(testrel, target_branch):
print 'Yes'
您是在测试1个字符串还是2个字符串?
target\u branch
是什么样子的?@fourthbird target\u branch变量值可能是release/4.8.0或r11\u i13您正在测试1个字符串还是2个字符串?target\u branch
是什么样子的?@Thefourthbird target\u branch变量值可能是release/4.8.0或r11\u i13