首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Regex连一句都匹配第一句

Regex连一句都匹配第一句
EN

Stack Overflow用户
提问于 2019-04-23 09:00:42
回答 1查看 51关注 0票数 1

我有一个有趣的正则表达式问题。说我有这样的段落

Johannesburg (; Afrikaans: ; also known as Jozi, Jo'burg, and eGoli) is the largest city in South Africa and one of the 50 largest urban areas in the world. It is the provincial capital and largest city of Gauteng, which is the wealthiest province in South Africa. While Johannesburg is not one of South Africa's three capital cities, it is the seat of the Constitutional Court. The city is located in the mineral-rich Witwatersrand range of hills and is the centre of large-scale gold and diamond trade.

该正则表达式(^.*?[a-z]{2,}[.!?])\s+\W*[A-Z]能够很好地根据句子构造逻辑找到第一句。当我只有一句这样的话时,问题就来了。

Johannesburg (; Afrikaans: ; also known as Jozi, Jo'burg, and eGoli) is the largest city in South Africa and one of the 50 largest urban areas in the world.

它与这句话不匹配是可以理解的,因为后面没有别的句子。我现在的问题是如何调整这个表达式,使其适用于这两种情况?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-23 09:02:49

您可以使用交替 (^.*?[a-z]{2,}[.!?])(?:\s+\W*[A-Z]|$)来匹配所需的逻辑或断言字符串$的末尾。

代码语言:javascript
复制
(^.*?[a-z]{2,}[.!?])(?=\s+\W*[A-Z]|$)

Regex演示

如果开始时不需要捕获组(),也可以省略它,并使用正的前瞻 (?=来获得匹配:

代码语言:javascript
复制
^.*?[a-z]{2,}[.!?](?=\s+\W*[A-Z]|$)

Regex演示

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55807681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档