我想在 python 中拆分字符串。
示例字符串:
Hi this is ACT I. SCENE 1 and SCENE 2 and this is ACT II. SCENE 1 and SCENE 2 and more
进入以下列表:
['Hi this is', 'ACT I. SCENE 1', 'and', 'SCENE2', 'and this is', 'ACT II. SCENE 1',
'and' , 'SCENE 2', 'and more']
有人可以帮我构建正则表达式吗?我构建的是:
(ACT [A-Z]+.\sSCENE\s[0-9]+)]?(.*)(SCENE [0-9]+)
但这不能正常工作。
最佳答案
如果我正确理解了您的要求,您可以使用以下模式:
(?:ACT|SCENE).+?\d+|\S.*?(?=\s?(?:ACT|SCENE|$))
Demo .
分割:
(?: # Start of a non-capturing group.
ACT|SCENE # Matches either 'ACT' or 'SCENE'.
) # Close the non-capturing group.
.+? # Matches one or more characters (lazy matching).
\d+ # Matches one or more digits.
| # Alternation (OR).
\S # Matches a non-whitespace character (to trim spaces).
.*? # Matches zero or more characters (lazy matching).
(?= # Start of a positive Lookahead (i.e., followed by...).
\s? # An optional whitespace character (to trim spaces).
(?:ACT|SCENE|$) # Followed by either 'ACT' or 'SCENE' or the end of the string.
) # Close the Lookahead.
Python 示例:
import re
regex = r"(?:ACT|SCENE).+?\d+|\S.*?(?=\s?(?:ACT|SCENE|$))"
test_str = "Hi this is ACT I. SCENE 1 and SCENE 2 and this is ACT II. SCENE 1 and SCENE 2 and more"
list = re.findall(regex, test_str)
print(list)
输出:
['Hi this is', 'ACT I. SCENE 1', 'and', 'SCENE 2', 'and this is', 'ACT II. SCENE 1', 'and', 'SCENE 2', 'and more']
关于python - 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743530/