Warning: This is not an article detailing how to write regular rules.
One, regular expression
- Time: hours 00-23
'/(^[0-1][0-9]$)|(^2[0-3]$)/';
- Time: minutes 00-59
'/^[0-5][0-9]$/';
- Mobile phone number: the beginning of 1, the second is 3 or 4 or 5 or 7 or 8, the last 9 digits end
'/^1[3|4|5|7|8]\d{9}/';
- mailbox
'/^[\w-]{4,}@[\w]+\.(com|cn)$/';
Two, PHP regular method
preg_match()
The return value matches 0 or 1, and the search stops after the first match.$str = 'abcdef'; //用法一,根据返回值判断字符串是否符合正则 echo preg_match('/abc/',$str); #输出1 //用法二,传入第三个参数,取址生成一个数组。 //一般来说,我们只关心匹配到的数组第0项,为正则匹配到的结果。 //如果使用括号,会依次拆分匹配项。 preg_match('/(bc)(de)/',$str,$match); print_r($match); //Array ( [0] => bcde [1] => bc [2] => de )
preg_match_all()
Similar to the above, the return value matches 0 or n.$str = 'ABCdeABC'; //用法一 echo preg_match_all('/ABC/',$str);#输出2 //用法二,match变成二维数组。 preg_match_all('/ABC(de)?/',$str,$match); print_r($match); //[['ABCdeABC','ABC'],['de',null]]
preg_replace()
Return the replaced string$str = 'ABCdeABC'; echo preg_replace('/ABC/','abc',$str);# 输出abcdeabc
preg_grep()
Return the matched array$arr1 = ['ABCdeABC','abc','ABC']; $arr2 = preg_grep('/ABC/',$arr1); print_r($arr2); //Array ( [0] => ABCdeABC [2] => ABC )
Three, JS regular writing
- Grammatical directness
/pattern/attributes
var str = 'abc123de'; /[a-z]/g; // 注意,
- Syntax for creating RegExp objects
new RegExp(pattern, attributes)
var regexp = new RegExp(/[a-z]/,'g');
Note 1: The regularity of JS does not need to be enclosed in single or double quotation marks.
Note 2: Regarding attributes
i, perform a case-insensitive matching.
g Perform a global match (find all matches instead of stopping after the first match is found).
m Perform multi-line matching.
Four, JS regular method
regexp.test()
Retrieval, whether the string conforms to the regular expression, return true or false/abc/i.test('ABCdeABC'); //true
regexp.exec()
Match, return if nonenull
.var str = "ABCdeABC"; var regexp = new RegExp("ABC","g"); var result; while ((result = regexp.exec(str)) != null) { console.log(result,result.index,regexp.lastIndex); }
Five, the regularity in the JS string method
str.search()
Search, return the position of the first substring that matches the regular, without returning -1.var str = 'ABCdeABC'; str.search(/BC/);//返回1 //如果明确搜索什么,还是用indexOf('BC')吧...
str.match()
Match, return the matched array, otherwise returnnull
.str.match(/abc/ig);//返回 ['ABC','ABC']
str.replace()
Replace, return the replaced stringstr.replace(/abc/i,"");//返回deabc str.replace(/abc/ig,"");//返回de //隐藏手机号中间四位 '15388880131'.replace(/(\d{3})(\d{4})(\d{4})/,"$1****$3"); //返回153****0131,这里$1,$2,$3分别代表3个()的匹配项。