正则表达式匹配除括号中的所有单词 - javascript [英] Regex to match all words except those in parentheses - javascript

查看:192
本文介绍了正则表达式匹配除括号中的所有单词 - javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下正则表达式匹配所有单词:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆