我有这样的文字:
Habitación 101
正如你所看到的,有一个带有重音符号的字母:ó
我正在寻找一个正则表达式,当单词不带重音时也能匹配,即“habitacion”。
我正在使用 JavaScript 的 new RegExp(keyword, 'u')
。
最佳答案
那么只需使用 Habitaci[ó|o]n
作为正则表达式。
const regex = new RegExp('Habitaci[ó|o]n', 'gi');
其中 [ó|o]
匹配列表 ó|o
中的单个字符。
这是一个演示:
const regex = new RegExp('Habitaci[ó|o]n', 'gi');
const str = `Habitación
Habitacion`;
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.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
关于javascript - 匹配的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49607668/