Regex Shortest Possible Match
Given: A 1234 AAAAAA AAAAAA 1234 7th XXXXX Rd XXXXXX I want to match: 1234 7th XXXXX Rd Using nothing more than Rd and \d+ so i tried: \d+.*?Rd but it matches starting from the
Solution 1:
You are using more than Rd
and \d+
when you add .*
which will match anything. If you can assume NUMBER-SPACE-SOMETHING-Rd
as the format - then you could add \s
to the mix and use
/(\d+\s+\d+.*?Rd)/
console.log('A 1234 AAAAAA AAAAAA 1234 7th XXXXX Rd XXXXXX'.match(/(\d+\s+\d+.*?Rd)/g))
Solution 2:
Use the following pattern:
^.*(1234 7th.*?Rd).*$
Explanation:
^.*from the startof the greedily consume everything until
(12347th capture from the last occurrence of12347th
.*?Rd) then non greedily consume everything until the first Rd
.*$ consume, but don't capture, the remainder of the string
Here is a code snippet:
var input = "A 1234 AAAAAA AAAAAA 1234 7th XXXXX Rd XXXXXX";
var regex = /^.*(1234 7th.*?Rd).*$/g;
var match = regex.exec(input);
console.log(match[1]); // 1234 7th XXXXX Rd
Post a Comment for "Regex Shortest Possible Match"