Regex.exec只显示第一次出现



Im使用以下正则表达式:

b([a-zäöüßA-ZÄÖÜ][^s]*)

对于字符串"Choriner Straße 12",如果我在regex101中测试它,它的匹配"Chorinner Strałe"。这正是我所需要的。但如果我在的代码中使用它

regex.exec("Choriner Straße 12")

代码:

const street_regex = new RegExp('\b([a-zäöüßA-ZÄÖÜ][^\s]*)/g');

它的回归只是"合唱团"。我不知道怎么了。。。你能帮我吗?

请参阅有关RegExp函数的MDN文档。

new RegExp(pattern[, flags])

标志需要作为第二个参数传递,也不需要在表达式末尾使用/FLAGS

const street_regex = new RegExp('\b([a-zäöüßA-ZÄÖÜ][^\s]*)', 'g');

…但您不应该首先使用RegExp构造函数。字符串转义使尝试读取变得可怕,而且它与简单的regexp文本相比没有任何好处。

const street_regex = /b([a-zäöüßA-ZÄÖÜ][^s]*)/g;

好吧,如果我从你的问题中得到正确的答案,这应该可以。

const getAddressWithoutNumber = fullAddress => {
const result = /(?![sd].+).+?(S+).+(?=sd.+)/igm.exec(fullAddress);
return result && result[0] || null;
}
console.log(getAddressWithoutNumber('123 Choriner Straße 12')); // outputs "Choriner Straße"

下面是一个使用/regex/语法的工作示例:

var regex = /b([a-zäöüßA-ZÄÖÜ][^s]*)/g
while((match = regex.exec("Choriner Straße 12")) !== null) {
console.log('The full match object:', match);
console.log('The actual result:', match[0]);
}

好吧,我发现,不是你的正则表达式不起作用,而是我的代码。我找到了正确的正则表达式,但还有一个问题。这是代码:

const regex = /b([a-zäöüßA-ZÄÖÜ][^s]+)/g;
const str = `Choriner Straße 12`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
for (var i = 0; i < m.length; i++) {
console.log(i,m)
}
}

这是我控制台上的结果(for循环(:

["Choliner","Choriner",索引:0,输入:"Choriner-Straße 12",组:未定义]runner-4.1.7.min.js:1 1(2(["Choriner","Chorinner",索引:0,输入:"Choriner-Straße 12",组:未定义]runner-4.1.7.min.js:10(2(["Straße","Stra",索引:9,输入:"Choriner Strałe 12",组:未定义]runner-4.1.7.min.js:11(2(["Straße","Stra 223; e",索引:9,输入:"Choriner Strałe 12",组:未定义]

正如您所看到的,regex与我想要的完全匹配,但我需要匹配为onw word。。。

最新更新