Last active
November 8, 2017 07:09
-
-
Save Tsutou/97e7c0bbf309dec7c86fc528ac92e081 to your computer and use it in GitHub Desktop.
正規表現から逃げない [初学者向け] ref: http://qiita.com/Tsutou/items/1c04a2abe9fcc276740d
This file contains 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
$str = "abcd\n"; // 最後に改行があります | |
var_dump(preg_match('/cd$/', $str)); // int(1) 改行があってもマッチしてしまいます | |
var_dump(preg_match('/cd$/D', $str)); // int(0) | |
var_dump(preg_match('/cd\z/', $str)); // int(0) |
This file contains 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
//文字列置換(/-/で-にマッチするものを、空文字に置換) | |
//=>つまり、ハイフンが含まれていれば取り除くという処理 | |
var post = '090-1234-5678'; | |
post.replace(/-/, ""); | |
=> '09012345678' | |
//文字列抽出(\dは数字にマッチするか,{}は桁数マッチ,$は末尾からマッチ) | |
//=>つまり、下四桁を抽出して切り出す処理、「\d」による判定が後ろから4回発生するということ。 | |
var birth = "19910422"; | |
birth.match(/\d{4}$/); | |
=> "0422" |
This file contains 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
<?php | |
// デリミターに / を使います | |
preg_match('/\d{4}/', '1234'); | |
// デリミターは変更できます | |
preg_match('@\d{4}@', '1234'); | |
// たとえば / がたくさん含まれる場合は変えたほうが読みやすいです | |
preg_match('|(/\d*)+|', '/1/2/3') |
This file contains 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
#gsubは当てはまるものすべてを置換。(subは最初の1つ) | |
post = '090-1234-5678' | |
post = post.gsub(/-/, "") | |
=> '09012345678' | |
birth = "19910422" | |
birth = birth.match(/\d{4}$/) | |
p birth | |
=> #<MatchData "0422"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment