正则表达式以匹配双引号中的单引号(单独)

Regex to match single quotes within double quotes (separately)?

本文关键字:单引号 单独 正则表达式      更新时间:2023-09-26

如何编写与此匹配的regex(见箭头):

"this is a ->'<-test'" // note they are quotes surrounding a word

和其他匹配这个?

"this is a 'test->'<-"

在JavaScript中?(然后,比如说,用双引号替换它们?

我想将它们与两个正则表达式分别匹配。

第一种情况

/''b/

正则表达式演示

"this is a 'test' there is another 'test'".replace(/''b/g, '"'))
=> this is a "test' there is another "test'

第二种情况

/'b'/

正则表达式演示

"this is a 'test' there is another 'test'".replace(/'b'/g, '"'))
=> this is a 'test" there is another 'test"

对于第一种情况:

var str = '"this is a ''test''"';
var res = str.replace(/'/, "#");
console.log(res);
=> "this is a #test'"

对于第二种情况:

var str = '"this is a ''test''"';
var res = str.replace(/(.*(?='))'/, "$1#");
console.log(res);
=> "this is a 'test#"

还要了解第二种情况只考虑最后一种'第一种情况只会考虑第一种'.

更新:

如果你想用一些东西替换第一个'的所有出现,试试这个:

var str = '"this is a ''test'' there is another ''test''"';
var res = str.replace(/'('w)/g, "#$1");
console.log(res);
=> "this is a #test' there is another #test'"

对于第二次出现,请尝试以下操作:

var str = '"this is a ''test'' there is another ''test''"';
var res = str.replace(/('w)'/g, "$1#");
console.log(res);
=> "this is a 'test# there is another 'test#"

这当然是一种非常具有操纵性的方法,您可能会在这里和那里遇到异常。恕我直言,使用正则表达式并执行此操作本身是一种过于复杂的方法

对于给定的字符串"this is a ->'<-test'"

"this is a ->'<-test'".replace(/'/g,"'""); // does both at the same time
// output "this is a ->"<-test""
"this is a ->'<-test'".replace(/'/,"'"").replace(/'/,"'"") // or in two steps
// output "this is a ->"<-test""
// tested with Chrome 38+ on Win7

第一个版本中的g执行全局替换,以便将所有'替换为'"(反斜杠只是转义字符)。第二个版本仅替换第一个匹配项。

我希望这有帮助

如果你真的想要匹配一次第一个和一次最后一个(不选择/替换第一个),你必须做这样的事情:

"this is a ->'<-test'".replace(/'/,"'""); // the first stays the same
// output "this is a ->"<-test'"
"this is a ->'<-test'".replace(/(?!'.+)'/,"'""); // the last
// output "this is a ->'<-test""
// tested with Chrome 38+ on Win7