測試了在 php 、 javascript 、 ruby、python 都可以用。
今天假設我要尋找使用者的 facebook id
facebook.com/profile.php?id=1234
fb.me/profile.php?id=1234
fb.me/1234
正規表達式這樣子寫:
*
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
girvan@JARVIS:~$ php -r '$p = "/(fb\.me\/|facebook\.com\/)(profile\.php\?id=|groups\/)(\d+)/"; | |
> $s = "facebook.com/profile.php?id=1234"; | |
> preg_match($p, $s, $m); | |
> var_dump($m);' | |
array(4) { | |
[0]=> | |
string(32) "facebook.com/profile.php?id=1234" | |
[1]=> | |
string(13) "facebook.com/" | |
[2]=> | |
string(15) "profile.php?id=" | |
[3]=> | |
string(4) "1234" | |
} |
真正想要的資料是在 $match[3] 才拿得到,而 $match[1] 和 $match[2] 其實都是垃圾。
如果在原本的 (match) 改成 (?:match)? 就可以不 match 到了
*
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
girvan@JARVIS:~$ php -r '$p = "/(?:fb\.me\/|facebook\.com\/)?(?:profile\.php\?id=|groups\/)?(\d+)/"; | |
> $s = "facebook.com/profile.php?id=1234"; | |
> preg_match($p, $s, $m); | |
> var_dump($m);' | |
array(2) { | |
[0]=> | |
string(32) "facebook.com/profile.php?id=1234" | |
[1]=> | |
string(4) "1234" | |
} |
中間寫再多,永遠只拿 $match[1] ,是不是很方便呢?