简体   繁体   English

Javascript 正则表达式 - 括号引用

[英]Javascript Regex - Quotes to Parenthesis

I'd like to somehow replace the string sequence "*" with (*) using a regex in Javascript.我想以某种方式使用 Javascript 中的正则表达式将字符串序列“*”替换为 (*)。 Replacing things between quotes to be between opening and closing parenthesis.将引号之间的内容替换为左括号和右括号之间的内容。

For example "apple" to (apple)例如“苹果”到(苹果)

Any ideas?有任何想法吗?

Try something like:尝试类似:

str.replace(/"(.*?)"/g, function(_, match) { return "(" + match + ")"; })

Or more simply或者更简单

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

Note the "non-greedy" specifier ?注意“非贪婪”说明符? . . Without this, the regexp will eat up everything including double quotes up until the last one in the input.没有这个,正则表达式将吃掉包括双引号在内的所有内容,直到输入中的最后一个。 See documentation here .请参阅此处的文档。 The $1 in the second fragment is a back-reference referring the first parenthesized group.第二个片段中的$1是引用第一个括号组的反向引用。 See documentation here .请参阅此处的文档。

You could try something like你可以尝试类似的东西

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

Example例子

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

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

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

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