如何用正则表达式捕获句子及标点?解决部分句子未捕获问题
Here's a regex that will capture all three sentences along with their ending punctuation (including newlines):
(?'s'.*?)(?'p'(?:[.!]\n?|\n))
Breakdown:
(?'s'.*?): This non-greedy named group (s) grabs the main sentence content, stopping at the first ending marker (either punctuation or newline).(?'p'(?:[.!]\n?|\n)): The named group (p) captures the ending:[.!]\n?: Matches a period or exclamation mark, followed by an optional newline (covers your second and third lines).|\n: Adds support for lines that end only with a newline (like your first title line, which has no trailing.or!).
This regex will correctly capture:
- First line:
s= the full title text,p= the newline character. - Second line:
s= the sentence before the period,p=.+ newline. - Third line:
s= the sentence before the exclamation mark,p=!+ newline.
If you're using Python, swap to Python-style named group syntax:
(?P<s>.*?)(?P<p>(?:[.!]\n?|\n))
内容的提问来源于stack exchange,提问作者craig
相关产品推荐
相关产品推荐

