Bread
Bread

Reputation: 443

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 first 1234 up to Rd instead of the second 1234, i thought .*? would match the shortest possible match, what am i doing wrong?

Upvotes: 0

Views: 1074

Answers (2)

Rob M.
Rob M.

Reputation: 36511

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))

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520888

Use the following pattern:

^.*(1234 7th.*?Rd).*$

Explanation:

^.*        from the start of the greedily consume everything until
(1234 7th  capture from the last occurrence of 1234 7th
.*?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

Upvotes: 1

Related Questions