如何在python中获取某些分隔符之间的所有子字符串

2024-06-17 12:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取与某些分隔符匹配的所有子字符串。我的问题是,我还需要在最后一次发生的字符结束。字符串必须介于以下任何字符之间:。, / , ? ,=,-,\

我试过这个正则表达式

pattern = re.compile(r"""[./?=\-_][^./?=\-_]+[./?=\-_]""")

在这个例子中:

-facebook=chat.messenger?

我无法获得substring=聊天。你知道吗

我只得到-facebook=和.messenger?你知道吗


Tags: 字符串refacebookchatsubstring字符messenger例子
2条回答

我的猜测是,这个表达式可能是我们想要开始的:

((?:[/?=_–.-])([a-z]+)(?:[/?=_–.-]))|([a-z]+)

Demo

测试

# 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.

看来是重叠造成了一些戏剧性的事情。如果使用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],并且[./?=\-_]是您指定的分隔符列表。你知道吗

希望这有帮助!你知道吗

相关问题 更多 >