渡一 25 正则表达式

2021/10/3 6:10:03

本文主要是介绍渡一 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

 



这篇关于渡一 25 正则表达式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程