正则表达式以匹配双引号中的单引号(单独)
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中?(然后,比如说,用双引号替换它们?
我想将它们与两个正则表达式分别匹配。
第一种情况
/''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
相关文章:
- Javascript/jQuery:用HTML span标记替换单引号中的文本
- 删除单引号字符转义
- 将字符串中的单引号替换为双引号
- JavaScript:单引号'导致错误
- 如何通过HTML将带有单引号的JSON从PHP传递到Javascript
- 如何在java脚本中用单引号写逗号分隔的值
- 使用jquery或regex,带点但不带点的拆分字符串位于单引号中
- 用空格替换单引号和其他符号
- javascript单引号/双引号
- 如何在字符串输入的 Html 元素中的双引号内编写单引号
- 使用javascript为#、单引号和双引号编码值
- JavaScript 相等操作对单引号字符串和数字都成功
- 对字符串使用单引号或双引号
- 如何在javasciipt中添加单引号到字符串,该字符串将在nodeJS中作为mysql插入命令执行
- JavaScript:当存在单引号时,用于替换双花引号的正则表达式失败
- 单引号 JSP 到 JavaScript 函数
- 在文本区域中,输入用jquery str.replacement()替换哭泣的smiley live的单引号
- Javascript 正则表达式将括号和单引号替换为斜杠
- 如何在javascript中的eval函数中添加单引号
- 正则表达式以匹配双引号中的单引号(单独)