正则表达式最短匹配

时间:2017-03-21 06:33:25

标签: javascript regex

假设:

Objective-C Generated Interface Header Name

我想要匹配:

A 1234 AAAAAA AAAAAA 1234 7th XXXXX Rd XXXXXX

仅使用1234 7th XXXXX Rd Rd 所以我尝试了:\d+

但它从第一个1234开始到第二个1234匹配,我认为\d+.*?Rd会匹配最短的匹配,我做错了什么?

2 个答案:

答案 0 :(得分:1)

使用以下模式:

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

<强>解释

^.*        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

以下是代码段:

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

答案 1 :(得分:1)

当您添加Rd时,您使用的内容超过\d+.*。如果您可以假定NUMBER-SPACE-SOMETHING-Rd作为格式 - 那么您可以将\s添加到混音中并使用

/(\d+\s+\d+.*?Rd)/

console.log('A 1234 AAAAAA AAAAAA 1234 7th XXXXX Rd XXXXXX'.match(/(\d+\s+\d+.*?Rd)/g))