如何写一个regex
来匹配这个(见箭头):正则表达式在双引号内(单独)与单引号匹配?
"this is a ->'<-test'" // note they are quotes surrounding a word
等相匹配呢?
"this is a 'test->'<-"
在JavaScript中? (然后,用双引号替换它们)
我想用两个正则表达式分别匹配它们。
如何写一个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(/(.*(?='))'/, "$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'"
第二occurence试试这个:
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#"
这ofcourse是一个非常操纵性的方法,你可能会面临异常情况。正则表达式和本身这样的恕我直言用法是一个过于复杂的方法
这是有希望的,但不会在字符串中找到所有''''。正如OP在评论中所提到的“这是一个'测试'',还有另一个'测试'''作为输入。在这里它只发现第一次发生 – nu11p01n73R
@ nu11p01n73R在这种情况下检查我的更新先生 – aelor
现在好了。如果你不介意请不要打电话给我先生不是那么古老:P – nu11p01n73R
第一种情况
/'\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"
我喜欢http://www.regexr.com/更好 –
@AliNaciErdem它是一个很棒的工具,但它只支持JavaScript,因为regex101支持php和python – nu11p01n73R
Depence弦上,对于给定的字符串"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
你想匹配他们seperatly或匹配字符串中的每个'''? – nu11p01n73R
@alexchenco分别与2个正则表达式。 – alexchenco
'“这是'测试'还有另外一个'测试'''那么这里发生了什么? – nu11p01n73R