python - 字符串的正则表达式

标签 python regex

我想在 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']

Try it online .

关于python - 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743530/

相关文章:

上个月的python日期

python - 通过向量化使用 for 和 if-else 加速 numpy 插值?

java - 正则表达式标签消除

python - 如何从字符串中提取 float

python - 使用 sphinx 生成文档时如何禁用 ssl 验证? (在代理后面工作)

python - 如何避免在 Django 模型上创建外键?

python - WinXP 上的 boost.python "DLL load failed",VisualStudio 2005

javascript - 使用 RegEx 获取最后一次出现

c# - 如何确定一个字符串是否是一个有效的变量名?

c# - 正则表达式性能问题