正则表达式求助:提取括号或@符号前的目标标识内容
Regex Solution to Extract Target Identifiers
Got it, let's break down how to extract those target identifiers (like j1, j2, j3, ab, cde) from your string. Looking at your input, each target either sits right before a parenthesized note followed by @ phi=..., or directly before @ phi=... without the parentheses. Here's a tailored regex solution:
The Regular Expression
(\w+)(?:\s*\([^)]*\))?\s*@
Breakdown of the Pattern
(\w+): Capture Group 1 – This grabs the identifier itself (matches letters, numbers, and underscores; if you know your identifiers only use letters/numbers, you can tighten this to[a-zA-Z0-9]+instead).(?:\s*\([^)]*\))?: Non-capturing optional group – This matches the optional parenthesized text (e.g.,(test1^3)):\s*: Matches any number of whitespace characters (including none)\(: Escaped left parenthesis[^)]*: Matches any character except a right parenthesis (so it stops at the closing))\): Escaped right parenthesis?: Marks this entire group as optional (covers cases where there's no parenthesized text, likej3 @ phi=2)
\s*@: Matches whitespace (if any) followed by the@symbol – this ensures we're targeting the correct position right before thephi=clause.
Usage Examples
Python
import re input_str = "CHECKING % x j1 (test1^3) @ phi=0 j2 (test2/3) @ phi=1 j3 @ phi=2 j1 (test1^3) @ phi=2 j2 (test2/3) @ phi=3 j3 @ phi=5 CHECKING % x ab (test1^3) @ phi=0 cde (test2/3) @ phi=1 fg @ phi=2 hij (test1^3) @ phi=2 kl (test2/3) @ phi=3 mn @ phi=5" pattern = r"(\w+)(?:\s*\([^)]*\))?\s*@" matches = re.findall(pattern, input_str) print(matches) # Output: ['j1', 'j2', 'j3', 'j1', 'j2', 'j3', 'ab', 'cde', 'fg', 'hij', 'kl', 'mn']
JavaScript
const inputStr = "CHECKING % x j1 (test1^3) @ phi=0 j2 (test2/3) @ phi=1 j3 @ phi=2 j1 (test1^3) @ phi=2 j2 (test2/3) @ phi=3 j3 @ phi=5 CHECKING % x ab (test1^3) @ phi=0 cde (test2/3) @ phi=1 fg @ phi=2 hij (test1^3) @ phi=2 kl (test2/3) @ phi=3 mn @ phi=5"; const pattern = /(\w+)(?:\s*\([^)]*\))?\s*@/g; const matches = []; let match; while ((match = pattern.exec(inputStr)) !== null) { matches.push(match[1]); } console.log(matches); // Output: ["j1", "j2", "j3", "j1", "j2", "j3", "ab", "cde", "fg", "hij", "kl", "mn"]
This regex will reliably extract all the identifiers you're targeting, regardless of whether they have a parenthesized note before the @ symbol.
内容的提问来源于stack exchange,提问作者Guiste
相关产品推荐
相关产品推荐

