小哥我最近在学习javaScript, 学到regular expression的时候见知识点有些杂乱,所以特别写篇博客做个总结。
定义
在javascript里定义reg exp有两种方法:
1) 用new exp : var exp1 = new exp("abc");
2) 直接在两个/中间放pattern: var exp2 = /abc/; //注意。。没有双引号哟, 加了就成string了
特殊字符
目测特殊字符和perl的是一样的。。直接拿来用就好
/d Digit characters
/w Alphanumeric characters (“word characters”)
/s Whitespace characters (space, tab, newline, and similar)
/D Characters that are not digits
/W Non-alphanumeric characters
/S Non-whitespace characters
. A period matches all characters except newlines
有个很简单的记的方法:
d = digit 所以是数字
w = word 所以是字母
s = space 所以是空格
所有大写全是反的。。
括号[]
在括号中放pattern 代表只要符合任意字符都为真。 (和java 或者 Perl都是一样一样的)
比如
复制代码 代码如下:
console.log(/[01]/.test("023424")); // true
console.log(/[01]/.test("13424")); // true
console.log(/[01]/.test("23424")); // false
复制代码 代码如下:
console.log(/[01]/.test("013424")); // true
console.log(/[01]/.test("13424")); // false
console.log(/[01]/.test("230424")); // false
console.log(/[01]/.test("230142401")); // true
GreedyReluctantPossessiveMeaning
X?X??X?+X, once or not at all
X*X*?X*+X, zero or more times
X+X+?X++X, one or more times
X{n}X{n}?X{n}+X, exactly n times
X{n,}X{n,}?X{n,}+X, at least n times
X{n,m}X{n,m}?X{n,m}+X, at least n but not more thanm times
复制代码 代码如下:
var name = "dear"
“oh, my dear”.replace(new Exp(name), "god"); // oh, my god
复制代码 代码如下:
var name = df[]vxv;
var expName = name.replace("/[^/w/s]/g","//$&");
"my name is df[]vxv".replace(new Exp(name), "Bob"); // my name is Bob
新闻热点
疑难解答
图片精选