正则表达式匹配所有的话,除了那些在括号 - JavaScript的
我使用正则表达式如下匹配所有的话:正则表达式匹配所有的话,除了那些在括号 - JavaScript的
mystr.replace(/([^\W_]+[^\s-]*) */g, function (match, p1, index, title) {...}
注意的话可以包含特殊字符,如德国日尔曼 如何匹配括号内的所有单词?
如果我有以下字符串:
here wäre c'è (don't match this one) match this
我想获得以下输出:
here
wäre
c'è
match
this
后面的空格并不真正的问题。 有没有一种简单的方法来实现这与JavaScript的正则表达式?
编辑: 我不能删除括号中的文本,因为最后一个字符串“mystr”也应该包含此文本,而字符串操作将在匹配的文本上执行。载于“myStr的”最后一个字符串看起来是这样的:
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"]
托马斯,复活这个问题,因为它有这样的没有提到一个简单的解决方案,并且没有按” t需要替换然后匹配(一步而不是两步)。 (发现你的问题而做一些研究的一般问题有关how to exclude patterns in regex)
这是我们简单的正则表达式(在看到它的工作on regex101,望着集团抓住在底部右图):
\(.*?\)|([^\W_]+[^\s-]*)
变更的左侧匹配完整(parenthesized phrases)
。我们将忽略这些匹配。右侧与第1组匹配并捕获单词,并且我们知道它们是正确的单词,因为它们与左侧的表达式不匹配。
这个程序演示了如何使用正则表达式(见online demo比赛):
<script>
var subject = 'here wäre c\'è (don\'t match this one) match this';
var regex = /\(.*?\)|([^\W_]+[^\s-]*)/g;
var group1Caps = [];
var match = regex.exec(subject);
// put Group 1 captures in an array
while (match != null) {
if(match[1] != null) group1Caps.push(match[1]);
match = regex.exec(subject);
}
document.write("<br>*** Matches ***<br>");
if (group1Caps.length > 0) {
for (key in group1Caps) document.write(group1Caps[key],"<br>");
}
</script>
参考
How to match (or replace) a pattern except in situations s1, s2, s3...
请你能帮我这个http://stackoverflow.com/questions/23797093/regex-email-validation-that-allows-only-hyphens-in-the-middle-of-the-domain-and – Axel
我不认为这是有可能使用单正则表达式,可能你需要首先用他们的内容去掉括号。 –
你是否需要考虑嵌套(像这个(或甚至这个))圆括号?如果是这样,您将不得不对嵌套施加上限或转到非基于RE的解决方案。 – Vatine
不需要考虑嵌套括号。可以有几个菜式,但它们不会嵌套。例如“(像这样)和like(this)” – thomasf