簡體   English   中英

正則表達式即使在一個句子上也匹配第一句

[英]Regex match first sentence even on one sentence

我有一個有趣的正則表達式問題。 說我有這樣的段落

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.

該正則表達式(^.*?[az]{2,}[.!?])\\s+\\W*[AZ]在基於句子構造邏輯查找第一個句子時效果很好。 當我只有這樣一句話時,問題就來了

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.

它與該句子不匹配,這是可以理解的,因為在此之后沒有其他句子開始。 我的問題是現在如何調整此表達式,使其適用於兩種情況?

您可以使用替代 (^.*?[az]{2,}[.!?])(?:\\s+\\W*[AZ]|$)匹配所需的邏輯或聲明字符串的結尾$

(^.*?[a-z]{2,}[.!?])(?=\s+\W*[A-Z]|$)

正則表達式演示

如果您一開始不需要捕獲組() ,則也可以忽略它,並使用正向前行 (?=僅獲得匹配項:

^.*?[a-z]{2,}[.!?](?=\s+\W*[A-Z]|$)

正則表達式演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM