javascript - 匹配的正则表达式

标签 javascript regex string

我有这样的文字:

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/

相关文章:

php - 在 PHP 中使用 preg_replace 时如何获得匹配项?

python - 在 Python 中将格式打印到文件

javascript - 如何在另一个JavaScript文件中包含一个JavaScript文件?

javascript - 与 Mysql、Php 和 Javascript 的动态导航链接

Python 2.6+ str.format() 和正则表达式

python - 如何获取字符串中的第一个单词

java - 模式的字符串匹配

java - Java中字符串相等性比较失败

javascript - 隐藏/显示某些 UL 元素?

javascript - 我想知道如何在 Jquery 加载 json 文件时在本地测试页面?