我的字符串形状如下:PW[Yasui Chitetsu]
;并且只想获得方括号内的名称:Yasui Chitetsu
。我正在尝试类似
[^(PW\[)](.*)[^\]]
作为正则表达式,但最后一个括号仍在其中。如何取消选择?对于这种情况,我认为我不需要花哨的东西。
答案 0 :(得分:1)
您尝试的方法存在一些问题:
asui Chitets
的字样。P
或W
开头的字符串上会有更多错误。例如,在PW[Paul McCartney]
中,您只能将ul McCartne
与该组匹配,并将ul McCartney
与该完全匹配。您想要这样的东西:
(?<=\[)([^]]+)(?=\])
这里是regex101 demo。
(?<=\[)
表示匹配必须以[
([^]]+)
匹配1个或多个不是]
的字符
(?=\])
表示匹配后必须紧跟]
以下是一些示例代码(来自上面的regex101链接):
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(?<=\[)([^]]+)(?=\])"
test_str = "PW[Yasui Chitetsu]"
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches):
matchNum = matchNum + 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)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
您在标题中提到在分号之间查找文本。可以使用相同的逻辑,从而获得正则表达式:
(?<=;)([^;]+)(?=;)