簡體   English   中英

正則表達式只捕獲第一場比賽

[英]Regex only capture first match

我想使用正則表達式解析字符串,字符串的示例是

Lot: He said: Thou shalt not pass!

我想把Lot抓起來, He said: Thou shalt not pass! . 但是,當我使用(.+): (.+)模式時,它返回

Lot: He said: Thou shalt not pass!

是否有可能捕獲He said: Thou shalt not pass使用正則表達式He said: Thou shalt not pass

您需要第一組的非貪婪(或懶惰)基數: (.+?): (.+)

有關http://www.regular-expressions.info/repeat.html 的更多詳細信息,“懶惰而不是貪婪”一章。

試試這個:

([^:]+):\s*(.*)
(?=.*?:.*?:)(.*?):(.*)

你可以用這個。

見演示。

http://regex101.com/r/rX0dM7/9

您應該使用標志 ig - i = 不區分大小寫,g = 在第一次匹配后不返回以及像“(. :) ?(. : .*)”這樣的表達式。

您可以在此處查看示例https://regex101.com/r/SXjg1b/1

下面一個工作。

([^:]+): (.+)

暫無
暫無

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

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