正则匹配需求:仅捕获开头指定数量括号项,排除后续括号内容
Got it, let's sort out this regex issue for you! The core problem here is that your current global regex grabs every parenthetical in the string, but you only want the leading consecutive ones at the start—ignoring any parentheses that show up later in the custom text.
Problem Breakdown
Your current regex /\(([^)]+)\)/g works globally, so it matches every () pair no matter where they are. That's why it's picking up (JAMIE HUTBER) from the middle of your description text, which isn't what you want. We need to restrict the match to only the parenthetical groups that appear right at the start of the string, one after another.
Solution Options
Option 1: Two-Step Match & Split (Most Readable)
This approach first captures all the leading parenthetical blocks as a single chunk, then splits them into individual items. It's easy to understand and maintain:
const testStr = "(374003) (C6-96738) (WR183186) R1|SALOON|DEFECTIVE|WiFiInfotainment|Hardware detects WIFI but unable to log in on the (JAMIE HUTBER) internet."; // Step 1: Match only the leading consecutive parenthetical groups const leadingMatch = testStr.match(/^(\([^)]+\)\s*)+/); if (leadingMatch) { // Step 2: Split into individual items and clean up whitespace const result = leadingMatch[0].trim().split(/\s+/); console.log(result); // Output: ["(374003)", "(C6-96738)", "(WR183186)"] }
Option 2: Single Regex with Lookarounds
If you prefer a one-regex solution, you can use lookarounds to ensure the parenthetical is part of the leading sequence:
const testStr = "(374003) (C6-96738) (WR183186) R1|SALOON|DEFECTIVE|WiFiInfotainment|Hardware detects WIFI but unable to log in on the (JAMIE HUTBER) internet."; const result = testStr.match(/(?<=^|\s)\(([^)]+)\)(?=(?:\s\([^)]+\))*\s)/g); console.log(result); // Output: ["(374003)", "(C6-96738)", "(WR183186)"]
How These Work
- For Option 1:
^(\([^)]+\)\s*)+anchors to the start of the string (^) and matches one or more instances of "parenthetical content + optional whitespace". Trimming and splitting on whitespace gives you clean individual items. - For Option 2: The lookahead
(?=(?:\s\([^)]+\))*\s)ensures that after the current parenthetical, there are only more leading parentheticals (followed by whitespace) before the non-parenthetical text starts. The lookbehind(?<=^|\s)ensures we're starting at the string's beginning or a whitespace boundary.
Test Result
Both methods will return exactly your desired output, ignoring the (JAMIE HUTBER) that appears later in the text.
内容的提问来源于stack exchange,提问作者Jamie Hutber

