javascript 正则表达式过滤掉某些字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31885080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:30:54  来源:igfitidea点击:

Regex to filter out certain characters

javascriptregex

提问by Mike. D

What would a regex string look like if you were provided a random string such as :

如果为您提供了一个随机字符串,那么正则表达式字符串会是什么样子,例如:

"u23ntfb23nnfj3mimowmndnwm8"

“u23ntfb23nnfj3mimowmndnwm8”

and I wanted to filter out certain characters such as 2, b, j, d, g, k and 8?

我想过滤掉某些字符,例如 2、b、j、d、g、k 和 8?

So in this case, the function would return '2bjd8'.

所以在这种情况下,函数将返回'2bjd8'.

There's a lot of literature on the internet but nothing straight to the point. It shouldn't be too hard to create a regex to filter the string right?

互联网上有很多文献,但没有什么是直截了当的。创建一个正则表达式来过滤字符串应该不会太难吧?

ps. this is not homework but I am cool with daft punk

附:这不是作业,但我对愚蠢的朋克很酷

回答by cн?dk

You need to create a regular expression first and then execute it over your string.

您需要先创建一个正则表达式,然后在您的string.

This is what you need :

这是你需要的:

var str = "u23ntfb23nnfj3mimowmndnwm8";
var re = /[2bjd8]+/g;
alert((str.match(re) || []).join(''));

To get all the matches use String.prototype.match()with your Regex.

要获得所有匹配项String.prototype.match(),请使用您的 Regex。

It will give you the following matches in output:

它将在输出中为您提供以下匹配项:

2 b2 j d 8

2 b2 jd 8

回答by hwnd

You could use a character class to define the characters.

您可以使用字符类来定义字符。

Using the match()method to analyze the string and then filter out the duplicates.

使用该match()方法对字符串进行分析,然后过滤掉重复项。

function filterbychr(str) {
  var regex = /[28bdgjk]/g
  return str.match(regex).filter(function(m,i,self) {
    return i == self.indexOf(m)
  }).join('')
}

var result = filterbychr('u23ntfb23nnfj3mimowmndnwm8') //=> "2bjd8"