简体   繁体   中英

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?

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM