所以我需要匹配被|. 所以,模式应该只是r"\|([^\|]*)\|",对吧?但是:
>>> pattern = r"\|([^\|]*)\|"
>>> re.match(pattern, "|test|")
<_sre.SRE_Match object at 0x10341dd50>
>>> re.match(pattern, " |test|")
>>> re.match(pattern, "asdf|test|")
>>> re.match(pattern, "asdf|test|1234")
>>> re.match(pattern, "|test|1234")
<_sre.SRE_Match object at 0x10341df30>
Run Code Online (Sandbox Code Playgroud)
它只匹配以|?开头的字符串。它在 regex101 上工作得很好,如果重要的话,这是 python 2.7。我可能只是在这里做一些愚蠢的事情,所以任何帮助将不胜感激。谢谢!
为了重现在https://regex101.com/上运行的代码,您必须单击Code Generator左侧的 。这将向您展示他们的网站正在使用什么。从那里您可以使用标志,或者使用您需要的功能re。
笔记:
re.MULTILINE默认标志re.finditer作为默认方法import re
regex = r"where"
test_str = "select * from table where t=3;"
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
Run Code Online (Sandbox Code Playgroud)
re.match将要匹配从开头开始的字符串。在您的情况下,您只需要匹配的元素,对吗?在这种情况下,您可以使用类似re.searchor 的东西re.findall,它会在字符串中的任何位置找到匹配:
>>> re.search(pattern, " |test|").group(0)
'|test|'
>>> re.findall(pattern, " |test|")
['test']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2102 次 |
| 最近记录: |