Javascript 正则表达式 - 括号引用 [英] Javascript Regex - Quotes to Parenthesis

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

问题描述

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

I'd like to somehow replace the string sequence "*" with (*) using a regex in Javascript. Replacing things between quotes to be between opening and closing parenthesis.

例如苹果"到(苹果)

有什么想法吗?

推荐答案

尝试类似:

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

或者更简单

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

注意非贪婪"说明符?.没有这个,正则表达式将吃掉包括双引号在内的所有内容,直到输入中的最后一个.请参阅此处的文档.第二个片段中的 $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. See documentation here.

这篇关于Javascript 正则表达式 - 括号引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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