【问题标题】:Replace string by 3 patterns "space", "and", "or"将字符串替换为 3 种模式“space”、“and”、“or”
【发布时间】:2019-04-24 04:03:23
【问题描述】:

我正在使用 Angular 6 开发一个项目,我需要使用带有正则表达式的替换方法将字符串替换为 3 种模式“空格”、“与”和“或”。我可以用“and”和“or”来做到这一点,但不能通过添加“空格”来做到这一点。用户将在搜索框中输入由 3 种模式中的任何一种分隔的单词。

这行得通:

const value = new RegExp(searchValue.toLowerCase().replace(/ and | or /g, '|'));

// Input: apple and pear or corn
// Output: /apple|pear|corn/

这不起作用:

const value = new RegExp(searchValue.toLowerCase().replace(/ \S+ | and | or /g, '|'));

我知道为了用空格替换你做.replace(/ /g, '|')),但我需要用“and”和“or”用同样的方法来替换空格。

如何做到这一点?先感谢您。

【问题讨论】:

  • 您可以将其用作正则表达式 ` 和 |或 | \s*` 虽然这会选择所有后续空格
  • 感谢您的回答。这有效: const value = new RegExp(searchVal.toLowerCase().replace(/ and | or |\s+/g, '|'));
  • 我的荣幸。玩得开心。

标签: javascript regex string typescript


【解决方案1】:

在正则表达式的末尾使用 \s+

错误 1:您使用 \S 代替 \s。

\S 匹配空格以外的字符。等价于 [^\f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]。

错误2:你在正则表达式的开头使用了\s

const value = new RegExp(searchValue.toLowerCase().replace(/ and | or |\s+/g, '|'));

let searchValue = "apple and pear or corn banana"
const value = new RegExp(searchValue.toLowerCase().replace(/ and | or |\s+/g, '|'));

console.log(value)

【讨论】:

  • 非常感谢。那行得通。我想顺序很重要。当我在正则表达式的乞求时得到 \s+ 时,它并没有给我预期的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
相关资源
最近更新 更多