问题描述
我正在使用以下正则表达式匹配所有单词:
I'm using the following regex to match all words:
mystr.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {...}
请注意,单词可以包含特殊字符,如德语元音。
如何匹配括号内的所有单词?
Note that words can contain special characters like German Umlauts.How can I match all words excluding those inside parentheses?
如果我有以下字符串:
here wäre c'è (don't match this one) match this
我想获得以下输出:
here
wäre
c'è
match
this
尾随空格并不重要。
使用javascript中的正则表达式有一种简单的方法来实现这一点吗?
The trailing spaces don't really matter.Is there an easy way to achieve this with regex in javascript?
编辑:
我无法删除括号中的文本,因为最后的字符串mystr也应包含此文本,而字符串操作将在匹配的文本上执行。最后一个字符串包含在myst中r看起来像这样:
I cannot remove the text in parentheses, as the final string "mystr" should also contain this text, whereas string operations will be performed on text that matches. The final string contained in "mystr" could look like this:
Here Wäre C'è (don't match this one) Match This
推荐答案
试试这个:
var str = "here wäre c'è (don't match this one) match this";
str.replace(/\([^\)]*\)/g, '') // remove text inside parens (& parens)
.match(/(\S+)/g); // match remaining text
// ["here", "wäre", "c'è", "match", "this"]
这篇关于正则表达式匹配除括号中的所有单词 - javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!