小哥我最近在學習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
Quantifiers
和java是一樣一樣一樣的。。 這個表很好。。小哥我一直喜歡用
| Greedy |
Reluctant |
Possessive |
Meaning |
| 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 |
expression object functions
1) test 這個很簡單,只用把要test的string放到test(...)裡,這個function就會return true/false 代表 match/unmatch
2) exec, 這個function返還null如果沒有找到match的string.. 如果找到了就會返還一個array. 這個裡邊包含按順序match的string
3) String.replace(expression1, string1) 這個function把expression中match的部分換成string1, string1裡可以用之前expression中的parenthesized group
,來替代其中的某個部分。 比如說"co-ol".replace(/[\w]+\-[\w]+/,"$2-$1"); //"ol-co" 一直可以用到$9
4)String.replace(expression, function) 這個是加強版,而且很強大, 可以通過function來定義任何你想要的output。具體用法不在這裡一一列出,請參考
點擊開啟連結
動態產生reg expression
當你想要用在reg exp裡的東西只有runtime才知道的時候,這個方法就可以適用
產生reg exp其實只需要用string 建好reg exp的樣子, 再用Exp的constructor就可以。 (在文章開頭的地方提到過)
例如:
複製代碼 代碼如下:
var name = "dear"
“oh, my dear”.replace(new Exp(name), "god"); // oh, my god
但是如果名字中有特殊字元可能會用在regular expression的時候, 往往上邊的方法會出錯。
所以, 在那種情況下,我們可以把input string的每一個字元的前邊都加上反斜線 比如:
複製代碼 代碼如下:
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