将多个正则表达式合并为一个。

huangapple go评论49阅读模式
英文:

combining multiple regex into single

问题

我有一个很长的字符串,我想用空字符替换其中的一些字符。
我有以下正则表达式:

  1. 首先,我想从字符串中删除所有的URL,对应的正则表达式是
    /(?:https?|ftp):\/\/[\n\S]+/i

  2. 接下来,我想删除所有以Car开头后跟着九个数字的单词。Car不区分大小写,对应的正则表达式是
    /car\s*\d{9}/i

  3. 最后,我想从字符串中删除所有的特殊字符,对应的正则表达式是
    /[^\w\s]/gi

所以我的输入字符串如下:

输入
Hell Test https://regex101.com with special Car123456789dgd cha cAr12345678racters @##!$#!@Hekki

输出Hell Test with special dgd cha cAr12345678racters Hekki

目前我需要进行三个单独的操作来完成这个任务,有没有办法将这些正则表达式合并成一个呢?

我尝试使用|来连接它们,但没有成功。
(/(?:https?|ftp):\/\/[\n\S]+/i)|(/car\s*\d{9}/i)|(/[^\w\s]/gi)

英文:

I have long string and I want to replace some chars with empty.
I have following regex

  1. 1st I want to remove all url from string, for which I have regex
    /(?:https?|ftp):\/\/[\n\S]+/i

  2. Next I want to remove all word which starts with Car followed by nine digits. Car word should case insensitive, regex for that /car\s*\d{9}/i

  3. And Last I want to remove all special chars from string, regex for that /[^\w\s]/gi

So my input string like below

Input
Hell Test https://regex101.com with special Car123456789dgd cha cAr12345678racters @##!$#!@Hekki

OutputHell Test with special dgd cha cAr12345678racters Hekki

currently I have to do 3 separate operation to do this, Is there any way I can combine these regex into one?

I try to join using | but didn't work.
(/(?:https?|ftp):\/\/[\n\S]+/i)|(/car\s*\d{9}/i)|(/[^\w\s]/gi)

答案1

得分: -1

使用|来组合:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const str = 'Hell Test https://regex101.com with special Car123456789dgd cha cAr12345678racters @##!$#!@Hekki';
console.log(str.replace(/(?:https?|ftp):\/\/[\n\S]+|car\s*\d{9}|[^\w\s]/gi, ''));

<!-- end snippet -->

英文:

Use | to combine:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const str = &#39;Hell Test https://regex101.com with special Car123456789dgd cha cAr12345678racters @##!$#!@Hekki&#39;;
console.log(str.replace(/(?:https?|ftp):\/\/[\n\S]+|car\s*\d{9}|[^\w\s]/gi, &#39;&#39;));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年8月9日 02:00:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76862121.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定