Javascript 正则表达式 - 括号引号
Javascript Regex - Quotes to Parenthesis
我想在 Javascript 中使用正则表达式以某种方式将字符串序列“*”替换为 (*)。将引号之间的内容替换为左括号和右括号之间。
例如"apple"到(苹果)
有什么想法吗?
试试这样的东西:
str.replace(/"(.*?)"/g, function(_, match) { return "(" + match + ")"; })
或者更简单地说
str.replace(/"(.*?)"/g, "()")
注意 "non-greedy" 说明符 ?
。如果没有这个,正则表达式将吃掉所有内容,包括双引号,直到输入中的最后一个。请参阅文档 here. The
in the second fragment is a back-reference referring the first parenthesized group. See documentation here。
你可以试试
replace(/"(.*?)"/g, "()")
例子
"this will be \"replaced\"".replace(/"(.*)"/, "()")
=> this will be (replaced)
"this \"this\" will be \"replaced\"".replace(/"(.*?)"/g, "()")
=> this (this) will be (replaced)
我想在 Javascript 中使用正则表达式以某种方式将字符串序列“*”替换为 (*)。将引号之间的内容替换为左括号和右括号之间。
例如"apple"到(苹果)
有什么想法吗?
试试这样的东西:
str.replace(/"(.*?)"/g, function(_, match) { return "(" + match + ")"; })
或者更简单地说
str.replace(/"(.*?)"/g, "()")
注意 "non-greedy" 说明符 ?
。如果没有这个,正则表达式将吃掉所有内容,包括双引号,直到输入中的最后一个。请参阅文档 here. The in the second fragment is a back-reference referring the first parenthesized group. See documentation here。
你可以试试
replace(/"(.*?)"/g, "()")
例子
"this will be \"replaced\"".replace(/"(.*)"/, "()")
=> this will be (replaced)
"this \"this\" will be \"replaced\"".replace(/"(.*?)"/g, "()")
=> this (this) will be (replaced)