小哥我最近在學習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","http://$&");
"my name is df[]vxv".replace(new Exp(name), "Bob"); // my name is Bob
新聞熱點
疑難解答
圖片精選