正则表达式中如何实现相同起始词的精确匹配?
Hey there! The issue you're running into is all about the order of your regex alternatives. Here's what's happening:
When you list shorter patterns like \sClaim\b or ^Claim\b before longer ones like \sClaim number\b, the regex engine will match the shorter "claim" first. Once it finds a match that fits, it doesn't bother checking the longer patterns later in the list. That's why you're only getting "claim" instead of the full "claim number".
Fix 1: Reorder your patterns to prioritize longer matches
The simplest fix is to move the longer phrases to the front of your alternative list. This way, the engine tries to match the longest possible valid string first:
var regex1 = RegExp(/(\sClaim number\b|^Claim number\b|\sClaim\b|^Claim\b|\sAssessment\b|^Assessment\b)/ , 'ig'); var str1 = 'what assessment claim number'; var array1; while ((array1 = regex1.exec(str1)) !== null) { console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`); }
Running this will now correctly match "claim number" instead of stopping at "claim".
Fix 2: Optimize your regex to reduce repetition
You can clean up the regex by grouping the common (^|\s) prefix instead of repeating it for every pattern. This makes the regex shorter and easier to maintain, while still ensuring longer phrases are prioritized:
// Use (^|\s) to handle both line start and preceding space var regex1 = RegExp(/(^|\s)(Claim number|Claim|Assessment)\b/ , 'ig'); var str1 = 'what assessment claim number'; var array1; while ((array1 = regex1.exec(str1)) !== null) { // array1[0] is the full match, array1[2] is the core phrase/word console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`); }
This version works the same way but is much cleaner—no more repeating ^ and \s for every single term!
内容的提问来源于stack exchange,提问作者Bijay Kumar Rai

