【问题标题】:Apply RegEx Only to Words that have length > 2仅将 RegEx 应用于长度 > 2 的单词
【发布时间】:2018-07-01 05:16:51
【问题描述】:

我正在寻找一个 RegEx 表达式,如果它们包含一个数字,则用 *** 替换整个单词,但前提是该单词超过 2 个字符。例如,

男孩又哭了 2 天! 12 12345

读作

男孩连续2天哭了*********! 12 *****

对于查找带数字的单词,以下表达式似乎有效:

[a-z]*\d+[a-z]*

但我想要一个解决方案,只找到长度大于 2 的更大单词。

【问题讨论】:

  • 我认为检查您匹配的单词的长度更容易。

标签: javascript regex


【解决方案1】:

你可以使用

\b(?=[^\d\W]*?\d)\w{3,}\b

a demo on regex101.com


崩溃了,这说
\b               # a word boundary
(?=[^\d\W]*?\d)  # a pos. lookahead, making sure there's a digit in the word
\w{3,}           # at least three word characters
\b               # another word boundary


您可以将其替换为固定模式(即***),但您需要一个用于字符串长度的函数。

【讨论】:

    【解决方案2】:

    replace使用回调函数并检查字长:

    var str = 'The boy cried w0lf aga1n for 2 days in row! 12 12345';
    var r = /[a-z]*\d+[a-z]*/g;
    
    var replacedStr = str.replace(r, function(v){
      return v.length <= 2 ? v : '*'.repeat(v.length);
    });
    
    console.log(replacedStr);

    编辑:如果替换总是字符串'***'(基于Jan's answer):

    var str = 'The boy cried w0lf aga1n for 2 days in row! 12 12345';
    var r = /\b(?=\w*\d)\w{3,}\b/g;
    
    var replacedStr = str.replace(r, '***');
    
    console.log(replacedStr);

    【讨论】:

    • 谢谢!是否可以在一个 RegEx 表达式中做到这一点?
    • 如果您的替换是固定长度的字符串,例如 3 个星号 '***' 代表任何单词,这是可能的,但由于您的替换取决于匹配的单词,所以不是
    • 我可以放宽这个要求——我们可以用 3 个星号
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2021-12-09
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多