![](/img/trans.png)
[英]JavaScript RegEx - replace first and last occurrence of a character
[英]Regex: ignore the first and last occurrence of " but not the rest
我有三個字符串:
{{“ ErrorMsg:[Microsoft] [ODBC SQL Server驅動程序] [SQL Server]用戶'blah'登錄失敗”}}
{{“ ErrorMsg:FATAL:角色\\” foobar \\“不存在\\ n”}}
“ {{\\” param1 \\“},{\\” param2 \\“}}”“
對於前兩種情況,我想得到一個1元素的數組,而對於第三種情況,我想得到一個2元素的數組( ['param1', 'param2']
)。 以下表達式適用於第一個字符串:
/[^{"}]+(?=\"})/g
但不適用於第二個字符串,因為里面還有兩個"
。如何使它起作用?
你可以在這里嘗試
{{“(。*)”}}返回完整字符串,不排除{{“和”}}
您需要以最簡單的方式提取匹配的組:
str.replace(/{{"(.*)"}}/g, function(m, g) {
console.log(g);
});
您可以使用此正則表達式:
/{\\?"([^}]+?)(?=\\?"})/g
匹配項將在捕獲的#1組中可用,您可以使用while
循環while
循環中調用regex.exec(str)
進行提取。
正則表達式分解:
{ # match {
\\? # match \ optionally
" # match a double quote
([^}]+?) # match any character that is not a } (lazy match)
(?=\\?"}) # lookahead to assert we have optional \ followed by "}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.