Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript正则表达式-括号中的引号_Javascript_Regex_String_Replace_Parentheses - Fatal编程技术网

Javascript正则表达式-括号中的引号

Javascript正则表达式-括号中的引号,javascript,regex,string,replace,parentheses,Javascript,Regex,String,Replace,Parentheses,我希望在Javascript中使用正则表达式以某种方式将字符串序列“*”替换为(*)。将引号之间的内容替换为左括号和右括号之间的内容 例如“苹果”到(苹果) 有什么想法吗 试试以下方法: str.replace(/"(.*?)"/g, function(_, match) { return "(" + match + ")"; }) 或者更简单地说 str.replace(/"(.*?)"/g, "($1)") 注意“非贪婪”说明符?。如果没有这一点,regexp将耗尽所有内容,包括双引号,

我希望在Javascript中使用正则表达式以某种方式将字符串序列“*”替换为(*)。将引号之间的内容替换为左括号和右括号之间的内容

例如“苹果”到(苹果)

有什么想法吗

试试以下方法:

str.replace(/"(.*?)"/g, function(_, match) { return "(" + match + ")"; })
或者更简单地说

str.replace(/"(.*?)"/g, "($1)")

注意“非贪婪”说明符
。如果没有这一点,regexp将耗尽所有内容,包括双引号,直到输入中的最后一个引号。见文件。第二个片段中的
$1
是指第一个括号中的组的反向引用。请参阅文档。

您可以尝试以下方法

replace(/"(.*?)"/g, "($1)")
示例

"this will be \"replaced\"".replace(/"(.*)"/, "($1)")
=> this will be (replaced)

"this \"this\" will be \"replaced\"".replace(/"(.*?)"/g, "($1)")
=> this (this) will be (replaced)

大家好,欢迎来到SO。请访问,了解如何提出未被关闭或否决的问题。提示:添加输入和预期的输出示例,再加上任何您拥有的代码,这可能会给您一个IDE。很抱歉,我认为正则表达式上下文中的*会很清楚。我将编辑问题。您确定您的带引号的字符串不包含转义引号吗?(
\“
)这对我来说很有用,非常感谢!编辑:我会接受这是正确的答案,但@nu11p01n73R的答案更简洁。非常感谢。不过这里的正则表达式从一开始就正确,并解释了原因