一道正则表达式问题求解释
本文介绍了一道正则表达式问题求解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
目的是将对话单引号替换成双引号,但不替换缩写时使用的单引号。
var text = "'I'm the cook,' he said, 'it's my job.'";
console.log(text.replace(/(^|\W)'|'(\W|$)/g, '$1"$2'));
// → "I'm the cook," he said, "it's my job."
代码第二行的替换部分为什么是$1"$2?
解决方案
看起来目的是替换字符串中单词外的单引号为双引号。
如果你的疑问是选择器
(^|W)'匹配的结果就是前面是字符串开头或者非单词字符(单词字符是指[^a-zA-Z0-9_])的单引号;
'(W|$)匹配的是后面是字符串结尾或者非单词字符的单引号。
如果你的疑问是replace语法
In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.
也就是说这里的 $1、$2 是匹配到的括号中的内容
http://www.ecma-international...
$n 是这么处理的:
The nth element of captures, where n is a single digit in the range 1 to 9. If n≤m and the nth element of captures is undefined, use the empty String instead. If n>m, the result is implementation-defined.
如果$1或者$2未匹配到内容此处就是空字符串,不会对结果有影响。
那,上面的正则有没有匹配到两个括号呢?用下面的代码验证:
var text = "'I'm the cook,' he said, 'it's my job.'";
function replacer(match,$1,$2){
console.log('match:['+match+']','$1:['+$1+']','$2:['+$2+']');
$1 = $1 || '';
$2 = $2 || '';
return $1+'"'+$2;
}
console.log(text.replace(/(^|\W)'|'(\W|$)/g, replacer));
//match:['] $1:[] $2:[undefined]
//match:[,'] $1:[,] $2:[undefined]
//match:[ '] $1:[ ] $2:[undefined]
//match:[.'] $1:[.] $2:[undefined]
//"I'm the cook," he said, "it's my job."
也就是说只匹配到了一个括号,所以$1是有值的,$2只是空字符串。
这篇关于一道正则表达式问题求解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文