【问题标题】:Sanitize stream from stdin using node.js使用 node.js 从标准输入清理流
【发布时间】:2019-09-25 16:22:47
【问题描述】:

我有这个脚本:

let stdin = '';

process.stdin
  .setEncoding('utf8')
  .resume()
  .on('data', d => {

   stdin+= d;
});


const regexs = [
  [/(?=.*[^a-zA-Z])[0-9a-zA-Z]{7,300}/g, function replacer(match, p1, p2, p3, offset, string) {
    return match.slice(0,2) + 'xxxxx' + match.slice(6);
  }]
];


process.stdin.once('end', end => {

  for(let r of regexs){
    stdin = stdin.replace(r[0], r[1]);
  }
  console.log(stdin);
});

我就是这样使用它的:

 echo "ageoageag ageagoie ag77eage" | node sanitize-stdin.js 

我明白了:

agxxxxxeag agxxxxxie agxxxxxge

但我真的只想替换长度为 6-300 的字符串(如果其中包含数字)。所以我正在寻找的输出是:

ageoageag ageagoie agxxxxxge

任何人都知道如何仅在字符串中至少有一个数字的情况下替换该字符串?

【问题讨论】:

    标签: node.js regex sanitization


    【解决方案1】:

    如果你的脚本被修改了,那么这个修改呢?

    在您的脚本中,replacer() 函数中的match 是拆分后的字符串。当输入"ageoageag ageagoie ag77eage" 时,ageoageagageagoieag77eage 的每个值都作为match 给出。 replacer() 将所有 match 的大小写返回为 match.slice(0,2) + 'xxxxx' + match.slice(6)。这样,agxxxxxeag agxxxxxie agxxxxxge 就会被返回。

    为了只处理match包括号码,这个修改怎么样?请修改replacer()的功能如下。

    发件人:

    return match.slice(0,2) + 'xxxxx' + match.slice(6);
    

    收件人:

    return /[0-9]/.test(match) ? match.slice(0,2) + 'xxxxx' + match.slice(6) : match;
    

    结果:

    ageoageag ageagoie agxxxxxge
    

    如果我误解了您的问题并且这不是您想要的结果,我深表歉意。

    编辑:

    如果输入的值用ageoageag ageagoie ag77eage这样的空格隔开,那么这个修改呢?在这个修改中,const regexs 没有被使用。

    发件人:

    for(let r of regexs){
      stdin = stdin.replace(r[0], r[1]);
    }
    

    收件人:

    stdin = stdin.split(" ").map(function(e) {
      return e.length > 6 && e.length <= 300 && /[0-9]/.test(e) ? e.slice(0,2) + 'xxxxx' + e.slice(6) : e;
    }).join(" ");
    

    【讨论】:

    • 我认为这可行,两步正则表达式通常比一个花哨的正则表达式简单得多
    • @Alexander Mills 感谢您的回复。很抱歉我的建议对您的情况没有用处。所以我提出了另外一个修改过的脚本。你能确认一下吗?另外,如果这对您的情况没有帮助,我深表歉意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多