如何将正则匹配结果用于另一正则?提取匹配结果中的数字
amount.match(/\d+\.?[0-9]{1,2}/) extract the number? Absolutely, but there's a tiny thing to watch out for: the first match() call returns an array (not a raw string) when your regex isn't using the global flag (g). So you'll need to access the actual matched string first using amount[0] before applying the second regex.
Let's walk through your example step by step:
const text = "I have usd **12** only."; // First match: returns an array containing the full matched string const amount = text.match(/(?:USD|usd)\s+.?\d+\.?[0-9]{1,2}/); if (amount) { // Always check if the match succeeded to avoid null errors // Extract the numeric value from the matched string const numberMatch = amount[0].match(/\d+\.?[0-9]{1,2}/); if (numberMatch) { const extractedNumber = numberMatch[0]; console.log(extractedNumber); // Outputs: "12" } }
This works because the second regex skips over non-digit characters (like the asterisks) and locks onto the numeric sequence in your first match result.
There are two common scenarios you might run into here:
1. Searching within the matched string (your use case)
This is exactly what you're trying to do. The workflow is straightforward:
- Run your first regex with
match()to get the result array. - Verify the result isn't
null(critical, sincematch()returns null if no match is found). - Grab the first element of the array (
result[0]) — that's the full string your first regex matched. - Apply your second regex to this string using
match()again to extract what you need.
2. Building a dynamic regex pattern from a match result
If you need to use part of the first match to construct the second regex pattern (instead of just searching inside the matched string), you can create a new RegExp object dynamically. Here's an example:
const text = "Price: USD 50, Discount: 10%"; // First, extract the currency code from the text const currencyMatch = text.match(/(USD|EUR|GBP)/); if (currencyMatch) { const currencyCode = currencyMatch[1]; // Build a regex to find the amount linked to that specific currency const dynamicRegex = new RegExp(`${currencyCode}\\s+(\\d+)`); const amountMatch = text.match(dynamicRegex); if (amountMatch) { console.log(`Amount for ${currencyCode}: ${amountMatch[1]}`); // Outputs: "Amount for USD: 50" } }
A quick heads-up: if your matched content includes regex special characters (like ., *, or ?), you'll want to escape them first with a helper function to avoid unintended behavior in your dynamic regex.
内容的提问来源于stack exchange,提问作者Johny

