令人惊讶,但我发现很难找到一个替换引号内文本的示例正则表达式。 E.g
john went for a 'walk'
john "walk" went for
- 您可以了解任何订单只会替换单词walk。
我确实找到了这个:Regular Expressions - how to replace a character within quotes但是对于我想要做的事情来说,这似乎很复杂。
答案 0 :(得分:2)
试用JavaScript正则表达式:
/(["'])[^]*?\1/g
这匹配双引号或单引号之间的任何内容。
针对您的具体情况:
var s = "john went for a 'walk'";
s.replace(/(["'])[^]*?\1/g, "run");
// "john went for a run"
和
var s = "john \"walk\" went for";
s.replace(/(["'])[^]*?\1/g, "run");
// "john run went for"
答案 1 :(得分:1)
怎么样
var string = "john went for a 'walk'";
var new_string = string.replace(/'([^;]*)'|"([^;]*)"/,"girl");