簡體   English   中英

查找模式的最后一次出現

[英]Find the last occurrence of a pattern

我正在嘗試匹配字符串中最后一次出現的模式。

我想在下面的字符串中得到括號中的最后一個字:

(不要與此匹配)而不是這個(但這個)

我試過以下,

\s(\((.*?)\))(?!\))

但這與兩次事件相匹配,而不僅僅是最后一次。 是否可以匹配最后一個?

匹配括號/\\(.*?\\)/g所有字符串並對結果進行后處理

您可以匹配滿足模式的所有字符串,並從結果數組中選擇最后一個元素。 沒有必要為這個問題提出復雜的正則表達式。

> "(Don't match this) and not this (but this)".match(/\(.*?\)/g).pop()
< "(but this)"

> "(Don't match this) and not this (but this) (more)".match(/\(.*?\)/g).pop()
< "(more)"

> "(Don't match this) and not this (but this) (more) the end".match(/\(.*?\)/g).pop()
< "(more)"

不希望結果中的() 只需使用slice(1, -1)來擺脫它們,因為模式修復了它們的位置:

> "(Don't match this) and not this (but this)".match(/\(.*?\)/g).pop().slice(1, -1)
< "but this"

> "(Don't match this) and not this (but this) (more) the end".match(/\(.*?\)/g).pop().slice(1, -1)
< "more"

使用.*搜索模式的最后一個實例

這是一個簡單的正則表達式的替代解決方案。 我們利用.*的貪婪屬性來搜索最匹配的模式匹配\\((.*?)\\) ,其中結果被捕獲到捕獲組1中:

/^.*\((.*?)\)/

請注意,此處不使用全局標志。 當正則表達式是非全局的(僅查找第一個匹配項)時, match函數返回捕獲組捕獲的文本以及主匹配。

> "(Don't match this) and not this (but this)".match(/^.*\((.*?)\)/)[1]
< "but this"

> "(Don't match this) and not this (but this) (more) the end".match(/^.*\((.*?)\)/)[1]
< "more"

當模式.*\\((.*?)\\)無法與索引0匹配時, ^是一種優化,以防止引擎“碰撞”以搜索后續索引。

您可以使用非捕獲括號來使用以前的匹配:

var string="(Don't match this) and not this (but this) definitely not this";
var last_match=string.match(/(?:.*\()([^\)]*)(?:\)[^\(]*)/)[1];

使用Web開發人員控制台測試:

< var string="(Don't match this) and not this (but this) definitely not this";
< string.match(/(?:.*\()([^\)]*)(?:\)[^\(]*)/)[1]
>"but this"

以下是測試鏈接: https//regex101.com/r/gT5lT5/2
如果您希望封閉括號成為匹配項的一部分,請查看https://regex101.com/r/gT5lT5/1

暫無
暫無

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

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