正则表达式 - 可选模式的所有内容,或者只是所有内容

Regex - everything up to an optional pattern, or just everything

我有以下文字:
这是一个空的序列。这是另一个

我正在尝试编写一个正则表达式,它可以获取所有内容,直到一个点后跟 space (\.\s),但是如果这个点后跟一个 space 不存在字符串,那我什么都想要。

示例:

这是一个空的序列。这是另一个
这是一个空的序列

这是一个空的序列这是另一个
这是一个空的序列这是另一个


我正在尝试这个,但即使字符串有一个点后跟一个 space 它也会得到一切:
This is a sequence (.*)(\.\s)?

PS:我在 python

中应用这个正则表达式

您可以试试这个正则表达式:

This is a sequence ((?:(?!\.\s).)*)
  • ((?:...)*)一组非捕获组,任意重复。
  • (?!\.\s). 任何带有前瞻性否定的字符,接下来的两个字符永远不会形成一个句号和一个 space

test cases

使用python:

import re

text = '''
This is a sequence of nothing. This is another
This is a sequence of nothing this is another
'''

result = re.findall(r'This is a sequence ((?:(?!\.\s).)*)', text)
print(result) # ['of nothing', 'of nothing this is another']

假设你想排除结果中的点,你可以尝试:

^This is a sequence (.*?)(?:\. |$)

在线查看demo

  • ^ - 起始行锚点。
  • This is a sequence - 字面意思是“这是一个序列”。
  • (.*?) - 包含 0+(惰性量词)字符的捕获组;
  • (?:\. |$) - 一个非捕获组,带有文字点后跟文字 space 结束行锚点。

import re
text =  "This is a sequence of nothing. This is another"
result = re.findall(r'^This is a sequence (.*?)(?:\. |$)', text)[0]
print(result) # of nothing