我正在尝试下一个代码,但似乎我做错了什么。
import re
lista = ["\\hola\\01\\02Jan\\05\\03",
"\\hola\\01\\02Dem\\12",
"\\hola\\01\\02March\\12\\04"]
for l in lista:
m= re.search("\\\\\d{2,2}\\\\\d{2,2}[a-zA-Z]+\\\\\d{2,2}\s",l)
if m:
print (m.group(0))
结果应该是第二个字符串。
我尝试过不使用 \s
但结果与所有字符串匹配。
最佳答案
您可以尝试这个正则表达式:
lista = [r"\hola\01\02Jan\05\03", r"\hola\01\02Dem\12", r"\hola\01\02March\12\04"]
>>> for l in lista:
... m = re.search(r"\\\d{2,2}\\\d{2,2}[a-zA-Z]+\\\d{2}$", l)
... if m:
... print m.group()
...
输出:
\01\02Dem\12
- 使用
r"..."
形式声明正则表达式并作为原始字符串输入 - 使用 anchor
$
避免匹配不需要的输入
关于python - 弄乱正则表达式 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32956898/