简体   繁体   English

正则表达式:匹配单词和特殊字符,除非用引号引起来

[英]Regex: Match words and special characters unless in quotes

I've already had a look at other questions which are nearly identical, and with a little customization I've found a solution that works in RegExr . 我已经看过其他几乎相同的问题,通过一些自定义,我找到了一个可在RegExr中使用的解决方案。 The problem is that it doesn't work in Javascript. 问题在于它在Javascript中不起作用。

Expression: ([^\\s]*"[^"]+"[^\\s]*)|[^"]?\\w+[^"]? 表达式: ([^\\s]*"[^"]+"[^\\s]*)|[^"]?\\w+[^"]?

Test string: +w1 @w2 (w3 (w4) @"w5 6" 测试字符串: +w1 @w2 (w3 (w4) @"w5 6"

Expected result: ['+w1', '@w2', '(w3', '(w4)', '@"w5 w6"'] 预期结果: ['+w1', '@w2', '(w3', '(w4)', '@"w5 w6"']

Javascript code: console.log(/([^\\s]*"[^"]+"[^\\s]*)|[^"]?\\w+[^"]?/g.exec(test_str)); Javascript代码: console.log(/([^\\s]*"[^"]+"[^\\s]*)|[^"]?\\w+[^"]?/g.exec(test_str));

Javascript result: ["+w1 ", undefined] (tested in FF15 and Chrome 22) Javascript结果: ["+w1 ", undefined] (在FF15和Chrome 22中测试)

I've looked up documentation on the MDN, but there are no other relevant flags than the global flag. 我在MDN上查找了文档,但是除了全局标志之外没有其他相关标志。 Just to try I've added multiline and case-insensitive flags, but they were no use. 只是为了尝试我添加了多行和不区分大小写的标志,但是它们没有用。

Any idea what makes it break in Javascript while it seems to work in RegExr? 知道是什么使它在RegExr中工作时在Javascript中中断吗? (And isn't Flash' Actionscript also ECMAScript, so shouldn't RegExr use the same regex engine?) In RegExr, the only enabled flag is the global flag. (而且Flash动作脚本也不是ECMAScript,所以RegExr不应使用相同的regex引擎吗?)在RegExr中,唯一启用的标志是全局标志。

Edit: Another issue is that "w1 \\"w2\\" w3" will be matched as two words while it should be one word. 编辑:另一个问题是"w1 \\"w2\\" w3"将被匹配为两个单词,而它应该是一个单词。 Any ideas? 有任何想法吗?

尝试:

console.log('+w1 @w2 (w3 (w4) @"w5 6"'.match(/[^"\s]+(?:".*"\S*)?/g));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM