We have seen in the previous topic that regex repetition is greedy, that is the regex engine tries to match as many ocurences of the repeated item as possible while still accounting for other parts of the regex pattern to match.
You can specify in your pattern that repetition should be non greedy. You just have to add a question mark (?) after the repetition quantifier like ??, *?, +?, {3,4}? etc
/\d+/ matches one or more digits. When applied to the input string dfg783356qert, it selects the longest match possible 783356 even though there are shorter matches that satisfy the pattern like 83356, 356, 6 etc
let wordPttn = /\d+/; let targetString = "dfg783356qert";let result = targetString.match(wordPttn);console.log((result !== null ? `Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'` : `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
Output:
Pattern /\d+/ FOUND in 'dfg783356qert'. Matched string is '783356'
/\d+?/ too matches one or more occurences of a digit but matches as few digits as possible. When /\d+?/ is applied to ‘dfg783356qert’ it only matches the first digit ‘7’.
let wordPttn = /\d+?/; let targetString = "dfg783356qert";let result = targetString.match(wordPttn);console.log((result !== null ? `Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'` : `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
Output:
Pattern /\d+?/ FOUND in 'dfg783356qert'. Matched string is '7'
When /\d+q/ is applied to ‘dfg783356qert’ it matches the string ‘783356q’ as expected. But if you expect /\d+?q/ on the same input to match only ‘6q’, you would be wrong. It still matches ‘783356q’. Regular expressions are evaluated by trying to find the earliest position in the string where there is a match. If a match is found at an earlier location of a string, shorter matches starting at subsequent positions are never tried.
let wordPttn = /\d+?q/; let targetString = "dfg783356qert";let result = targetString.match(wordPttn);console.log((result !== null ? `Pattern ${wordPttn} FOUND in '${targetString}'. Matched string is '${result[0]}'` : `Pattern ${wordPttn} NOT FOUND in '${targetString}'`));
Output:
Pattern /\d+?q/ FOUND in 'dfg783356qert'. Matched string is '783356q'