我正在尝试获取与某些定界符匹配的所有子字符串。我的问题是,我也需要在最后一次出现的末尾使用该字符。字符串必须介于以下任何一个字符之间:。 ,/ ,? ,=,-,_
我尝试过此正则表达式
pattern = re.compile(r"""[./?=\-_][^./?=\-_]+[./?=\-_]""")
在此示例中:
-facebook=chat.messenger?
我无法获得子字符串= chat。
我只有-facebook =和.messenger吗?
答案 0 :(得分:1)
看起来重叠是造成某些戏剧性事件的原因。如果使用regex
模块(有望最终替换re
模块),则可以
import regex as re
delimiters = r'[./?=\-_]'
pattern = delimiters + r'[a-z]+' + delimiters
s = '-facebook=chat.messenger?'
print(regex.findall(pattern, s, overlapped=True))
# ['-facebook=', '=chat.', '.messenger?']
请注意,这假定所有字符都用[a-z]
小写,并且[./?=\-_]
是您指定的定界符列表。
希望这会有所帮助!
答案 1 :(得分:0)
我的猜测是,该表达式可能是我们可能想以的开头:
((?:[/?=_–.-])([a-z]+)(?:[/?=_–.-]))|([a-z]+)
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"((?:[/?=_–.-])([a-z]+)(?:[/?=_–.-]))|([a-z]+)"
test_str = "-facebook=chat.messenger?"
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)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.