【问题标题】:How to replace certain words without replacing the whitespace before it in regex如何在不替换正则表达式之前的空格的情况下替换某些单词
【发布时间】:2017-02-07 04:25:01
【问题描述】:

我想替换 javascript 中的某些单词,但它必须是准确的单词。例如,如果单词是 run,那么 running 不应该匹配。

当前正则表达式替换单词前面的空格。我怎样才能让它找到确切单词的所有情况(即使在句子的开头)而不替换空格,但忽略逗号、问号等?谢谢!

new RegExp('([^a-zA-Z0-9_-]|^)' + wa + '(?![a-zA-Z0-9_-])'

【问题讨论】:

  • 使用\b 匹配单词边界,不使用字符。

标签: javascript regex


【解决方案1】:

使用word boundary(\b) 断言单词边界。

new RegExp('\\b' + wa + '\\b')

或者替换为captured group值。

string.replace(new RegExp('([^a-zA-Z0-9_-]|^)' + wa + '(?![a-zA-Z0-9_-])'), '$1')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多