Regex无法提取指定模式间字符串问题求助
Fixing Your Regex to Extract Target Content
Let's get this sorted out! You're trying to pull the content between FX:1 and the first alphanumeric-mixed word (mndfgusadg202OL19010200785) from your string, expecting NEAT LIMITE as the result. Your current regex isn't working because of a couple of key issues—let's break it down and fix it.
What's Wrong With the Original Pattern?
Your regex FX:1 (.*) ((?=.*[0-9])(?=.*[a-zA-Z]))+ has two main problems:
- The
.*is a greedy match, which means it will gobble up everything fromFX:1all the way to the end of the string instead of stopping at the first alphanumeric word. - The positive lookahead at the end doesn't correctly target the alphanumeric word—it's checking for any presence of numbers and letters in the entire remaining string, not the next word specifically.
The Correct Regex Solution
We need a non-greedy match for the content between FX:1 and our target word, plus a precise lookahead to identify when we've reached that first alphanumeric-mixed word. Here's the working code:
var str = "CR 1513II2255651 202OL19010200785 FX:1 NEAT LIMITE mndfgusadg202OL19010200785 NEAT LIMITED NEAT LIMITED HKD 52194.2"; // Regex breakdown: // FX:1 → Matches the exact prefix we're starting from // (.*?) → Non-greedy match of any characters, stops at the first match of the lookahead // (?=\s+[a-zA-Z0-9]*[a-zA-Z][0-9][a-zA-Z0-9]*) → Positive lookahead to find the next alphanumeric word var pattern = /FX:1 (.*?)(?=\s+[a-zA-Z0-9]*[a-zA-Z][0-9][a-zA-Z0-9]*)/; var matchResult = str.match(pattern); // Access the captured group for your desired content console.log(matchResult[1]); // Outputs: "NEAT LIMITE"
Regex Details
.*?: The non-greedy quantifier ensures we only match up to the first occurrence of our target condition, not the entire rest of the string.(?=\s+[a-zA-Z0-9]*[a-zA-Z][0-9][a-zA-Z0-9]*): This lookahead checks for:- One or more whitespace characters (
\s+) - A word that contains both letters and numbers (we enforce this by requiring at least one letter followed by at least one number, wrapped in optional alphanumeric characters on either side)
- One or more whitespace characters (
内容的提问来源于stack exchange,提问作者Ameya Salagre
相关产品推荐
相关产品推荐

