替换Javascript正则表达式中不包含单引号的双引号 [英] Replace double quotes not surrounded by single quotes in Javascript regex

查看:614
本文介绍了替换Javascript正则表达式中不包含单引号的双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我需要的是一个正则表达式,它只选择未被单引号括起来的双引号。 (这是为了在不破坏任何嵌套字符串的情况下快速重构双引号为单引号。)

Basically what I need is a regex expression that only selects double-quotes that are not surrounded by single-quotes. (This is in order to quickly refactor double-quote into single-quotes without breaking any nested strings).

示例(与在其中):

"foo" => 'foo'
'foo' => 'foo'
abc "foo" => abc 'foo'
foo "bar", "baz" => foo 'bar', 'baz'
abc 'foo "bar" baz' => abc 'foo "bar" baz'

所以在搜索这个问题时,我找到了< a href =https://stackoverflow.com/questions/38638039/replace-double-quotes-not-surrounded-by-single-quotes>如何在PCRE中执行此操作但我无法弄清楚如何将(* SKIP)(* F)转换为可用的Javascript Regex

So on searching for this question, I was able to find how to do this in PCRE but I wasn't able to figure out how to convert the (*SKIP)(*F) into usable Javascript Regex

我自己的Javascript尝试是:
/(?:('。* []。*')|)/ g 现场演示)。

My own Javascript attempt is: /(?:('.*["].*')|")/g (live demo).

第一个模式 /'.* []。*'/ 与我最终匹配得很好想要排除('foobarbaz'),但我不确定如何告诉表达式,如果匹配,则排除它。

The first pattern /'.*["].*'/ goes a good job matching what I eventually want to exclude ('foo "bar" baz') but I'm then unsure how to tell the expression that if this is matched, to exclude it.

我尝试过使用(?!)表达式但没有成功。

I've tried playing around with the (?!) expression with no success.

如果有人知道如何写一个更好的正则表达式或者有一个替代解决方案来解决这个问题我会很感激。

If anyone has an idea on how to do either write a better regex or have an alternative solution to the problem I'd appreciate it.

编辑:

作为附加信息,正则表达式用于搜索和替换WebStorm / PHPStorm中的函数以重构源代码。

As additional information, the regex expressions are being used for search and replace functions in WebStorm/PHPStorm to refactor source code.

推荐答案

你可以使用这个正则表达式:

You can use this regex:

"(?=(?:[^']*'[^']*')*[^']*$)

它将匹配单引号外的任何双引号,工作样本

It will match any double quotes outside single quotes, working sample.

诀窍是向前搜索一行单引号的行尾,如果找到奇数个单引号则不接受。

The trick is to search forward till the end of the line for a pair of single quotes, don't accept if odd number of single quotes is found.

这篇关于替换Javascript正则表达式中不包含单引号的双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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