簡體   English   中英

使用前瞻性獲取javascript中模式的最后一次出現

[英]using a lookahead to get the last occurrence of a pattern in javascript

我能夠構建一個正則表達式來提取模式的一部分:

var regex = /\w+\[(\w+)_attributes\]\[\d+\]\[own_property\]/g;
var match = regex.exec( "client_profile[foreclosure_defenses_attributes][0][own_property]"  );
match[1] // "foreclosure_defenses"

但是,我也有一種重復的模式,如下所示:

“ client_profile [lead_profile_attributes] [foreclosure_defenses_attributes] [0] [own_property]”

在那種情況下,我想忽略[lead_profile_attributes],而是像在第一個示例中一樣提取最后一次出現的部分。 換句話說,在這種情況下,我仍然想匹配“ foreclosure_defenses”。

由於所有模式都將類似於[(\\ w +)_ attributes],因此我嘗試進行前瞻,但它不起作用:

var regex = /\w+\[(\w+)_attributes\](?!\[(\w+)_attributes\])\[\d+\]\[own_property\]/g;
var match = regex.exec("client_profile[lead_profile_attributes][foreclosure_defenses_attributes][0][own_property]");
match // null

match返回null,這表示我的正則表達式無法正常工作。 我添加了以下內容:

\[(\w+)_attributes\](?!\[(\w+)_attributes\])

因為我只想匹配以下模式的最后一次出現:

[lead_profile_attributes][foreclosure_defenses_attributes]

我只想獲取foreclosure_defenses,而不是lead_profile。

我可能做錯了什么?

我想我在沒有積極前瞻的情況下就可以正常工作:

regex = /(\[(\w+)_attributes\])+/
/(\[(\w+)_attributes\])+/
match = regex.exec(str);
["[a_attributes][b_attributes][c_attributes]", "[c_attributes]", "c"]

我也可以通過不參與的小組實現這一目標。 chrome控制台的輸出:

var regex = /(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/;
undefined
regex
/(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/
str = "profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]";
"profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]"
match = regex.exec(str);
["profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]", "[properties_attributes][0]", "[other_stuff]"]

暫無
暫無

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

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