字符串解析求助:提取指定函数表达式的正则匹配问题
Got it, let's fix this regex issue for you. Your current pattern isn't accounting for the parentheses structure of the function calls, which is why it's not pulling out the values you need.
Correct Approach
You need a regex that specifically targets function call patterns (functionName(params)), where params can be empty or contain characters (as long as they don't include a closing parenthesis). Here's the working code:
const str = "Date()+Abs(9)Day()+45"; const arr = str.match(/\w+\([^)]*\)/g); console.log(arr); // Output: ["Date()", "Abs(9)", "Day()"]
Breakdown of the Regex
Let's break down what each part of /\w+\([^)]*\)/g does:
\w+: Matches one or more letters, numbers, or underscores (this captures the function name likeDate,Abs, orDay)\(: Escaped left parenthesis to match the literal(character (since parentheses are special in regex)[^)]*: Matches any number of characters except)— this captures everything inside the parentheses, whether it's empty (like inDate()) or has content (like9inAbs(9))\): Escaped right parenthesis to match the literal)characterg: The global flag, which tells the regex to find all matches in the string instead of stopping at the first one
Why Your Original Regex Failed
Your original pattern /\w+(\w+)/ is designed to match a word followed by another word (capturing the second one), which has nothing to do with the function call structure you're targeting. It can't recognize parentheses or the content inside them, so it won't pull out the full function calls you need.
内容的提问来源于stack exchange,提问作者Sagar Chaudhary

