正则表达式匹配双引号内的单引号(分别)?

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

如何写一个 regex 来匹配这个(见箭头):

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

和其他匹配吗?

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

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

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

第一种情况:

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(/(.*(?='))'/, "#");
console.log(res);

=> "this is a 'test#"

也明白第二种情况只考虑了最后一种情况' 而第一种情况只会考虑第一个 '.

更新:

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

var str = '"this is a \'test\' there is another \'test\'"';
var res = str.replace(/'(\w)/g, "#");
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, "#");
console.log(res);

=> "this is a 'test# there is another 'test#"

这当然是一种非常操纵性的方法,您可能会遇到到处裁剪的例外情况。恕我直言,使用正则表达式本身就是一种过于复杂的方法

第一种情况

/'\b/

Regex Demo

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

第二种情况

/\b'/

Regex Demo

"this is a 'test' there is another 'test'".replace(/\b'/g, '"'))
=> 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 进行了全局替换,因此它将所有 ' 替换为 \"(反斜杠只是转义字符)。第二个版本仅替换第一个版本。

希望对您有所帮助

如果你真的想要第一个和最后一个匹配(没有 selecting/replacing 第一个),你将不得不做这样的事情:

"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