其他分享
首页 > 其他分享> > 渡一 25 正则表达式

渡一 25 正则表达式

作者:互联网

\w     [0-9A-z_]
\W     [^\w]
\d     [0-9]
\D     [^\d]
\s      [\t\n\r\v\f]
\S     [^\s]
\b     单词边界
\B     非单词边界
.       [^\r\n]

量词 正则是贪婪的

n+  {1,infinity}
n*  {0,infinity}
n?  {0,1}
n{x}  {x} x个
n{x,y}  {x,y} x-y个
n{x,}  {x,infinity}

位置

^n
n$

方法

reg.test();
str.match();
var reg = /\w*/g;
var str = "abc";
str.match(reg) //["abc",""]


var reg = /^abc$/g; //以当前abc开头,并以当前abc结尾
var str = "abcabc";
str.match(reg) //null


//检验一个字符串首尾是否含有数字
var reg = /^\d|\d$/g;    //首或尾有数字
var reg = /^\d[\s\S]*\d$/g; //首尾都有数字
//前提是reg要加g否则值不变
reg.lastIndex //返回位置
reg.exec() //返回的数组里包括位置
reg.lastIndex=0 //更改位置

var str = "aaaa";
var reg = /(\w)\1\1\1/g; //["aaaa"]

var str = "aabb";
var reg = /(\w)\1(\w)\2/g;//["aabb"]

console.log(reg.exec(str));//["aabb","a","b"]
console.log(str.match(reg));//reg不加g["aabb","a","b"]
console.log(str.match(reg));//reg加g["aabb"]
var str = "ebdaabbbbcc";
console.log(str.search(reg));//[3] 返回匹配到的位置,失败返回-1
var str = "ebda2abbbbc3c";
var reg = /\d/g; //按重复的字母拆分数组
console.log(str.split(reg));//返回拆分后的数组
var str = "aa";
console.log(str.replace("a","b")) //"ba"
var reg = /a/g;
str.replace(reg,"b"); //bb


//aabb
var reg = /(\w)\1(\w)\2/g;
var str = "aabb";
str.replace(reg,"$2$2$1$1") //bbaa
str.replace(reg,function($,$1,$2){
    return $2+$2+$1+$1; //bbaa;
}) 


var str = "the-first-name"; //theFirstName
var reg = /-(\w)/g;
str.replace(reg,function($,$1){
    return $1.toUpperCase();
})
正向预查
var str = "abaaaaa" //查后面有b的a;
var reg = /a(?=b)/g; 
var reg = /a(?!b)/g; //["a","a","a","a","a"]
str.match(reg); //a



非贪婪匹配
var str = "aaaaaa";
var reg = /a+/g; //["aaaaaa"]
var reg = /a+?/g; //["a","a","a","a","a","a"]



练习 字符串去重 
var str = "aaaaaaabbbbbbbcccccc";
var reg = /(\w)\1*/g;
str.replace(reg,"$1")


数字科学计数法
var str = "100000000";
var reg = /(?=(\B)(\d{3})+$)/g;
console.log(str.replace(reg,"."));//100.000.000

 

标签:渡一,console,25,正则表达式,aabb,replace,str,var,reg
来源: https://www.cnblogs.com/lisa2544/p/15363318.html