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

时间:2015-01-05 08:29:46

标签: javascript regex

如何编写regex以匹配此内容(请参阅箭头):

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

和其他人匹配?

"this is a 'test->'<-"
在JavaScript中

? (然后,说,用双引号替换它们?)

我希望将它们与两个正则表达式分开匹配。

3 个答案:

答案 0 :(得分:3)

第一个案例

/'\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"

答案 1 :(得分:2)

第一种情况:

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#"

这是一种非常有操控性的方法,你可能会在这里和那里面临例外情况。恕我直言,使用正则表达式本身就是一种过于复杂的方法

答案 2 :(得分:1)

对于给定字符串"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
相关问题