如果我有一个字符串,其中有任何类型的非字母数字字符:

"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"

我如何在JavaScript中得到一个没有标点符号的版本:

"This is an example of a string with punctuation"

当前回答

在支持Unicode的语言中,Unicode Punctuation字符属性是\p{p}——为了便于阅读,通常可以缩写为\pP,有时也可以扩展为\p{Punctuation}。

您正在使用Perl兼容正则表达式库吗?

其他回答

如果您正在使用lodash

_.words('This, is : my - test,line:').join(' ')

这个例子

_.words('"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation"').join(' ')

我遇到过同样的问题,这个解决方案很管用,而且可读性很强:

var sentence = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var newSen = sentence.match(/[^_\W]+/g).join(' ');
console.log(newSen);

结果:

"This is an example of a string with punctuation"

诀窍是创建一个负集合。这意味着它匹配任何不在集合内的东西,即[^abc] -不是a, b或c

\W是任何非单词,所以[^\W]+将否定任何非单词char。

通过添加_(下划线),你也可以否定它。

让它全局应用/g,然后你可以通过它运行任何字符串,并清除标点符号:

/[^_\W]+/g

又漂亮又干净;)

这取决于你想要返回什么。我最近用了这个:

return text.match(/[a-z]/i);

它很简单,只是替换字符而不是单词:

.replace(/[^\w]/g, ' ')

下面是US-ASCII的标准标点符号:!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

对于Unicode标点符号(如大引号、em-dash等),可以很容易地匹配特定的块范围。一般标点符号块是\u2000-\u206F,补充标点符号块是\u2E00-\u2E7F。

放在一起,并正确转义,您将得到以下RegExp:

/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/

这应该可以匹配您遇到的任何标点符号。那么,来回答最初的问题:

var punctRE = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/g;
var spaceRE = /\s+/g;
var str = "This, -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
str.replace(punctRE, '').replace(spaceRE, ' ');

>> "This is an example of a string with punctuation"

US-ASCII来源:http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#posix

Unicode来源:http://kourge.net/projects/regexp-unicode-block