我想要一個 Javascript 正則運算式或任何可能的解決方案,對于給定的字串,查找以特定字串開頭并以特定字符結尾的所有子字串。回傳的子字串集可以是一個陣列。
該字串也可以嵌套在括號內。
var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";
開始 char = "myfunc" 結束 char = ")" 。這里的結束字符應該是第一個匹配的右括號。
輸出:帶引數的函式。
[myfunc(1,2),
myfunc(3,4),
myfunc(5,6),
func(7,8)]
我已經嘗試過了。但是,它總是回傳 null 。
var str = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))";
var re = /\myfunc.*?\)/ig
var match;
while ((match = re.exec(str)) != null){
console.log(match);
}
你能在這里幫忙嗎?
uj5u.com熱心網友回復:
我測驗了你的正則運算式,它似乎作業正常:
let input = "myfunc(1,2) and myfunc(3,4) or (myfunc(5,6) and func(7,8))"
let pattern = /myfunc.*?\)/ig
// there is no need to use \m since it does nothing, and NO you dont need it even if you use 'm' at the beginning.
console.log(input.match(pattern))
//[ "myfunc(1,2)", "myfunc(3,4)", "myfunc(5,6)" ]
如果你使用(?:my|)func\(. ?\),你也可以捕捉到 'func(7,8)'。
(?:my|)
( start of group
?: non capturing group
my| matches either 'my' or null, this will match either myfunc or func
) end of group
在此處測驗正則運算式:https ://regex101.com/r/3ujbdA/1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432558.html
標籤:javascript 正则表达式
下一篇:正則運算式前瞻n次python
