In computer science, regular expressions are used to describe or match a single string of strings that conform to a certain syntactic rule. In WEB development, regular expressions are usually used to detect and find and replace certain strings that comply with rules, such as detecting whether the user inputs E-mai format is correct, collecting page content that complies with rules, etc.
Today we use PHP and Javscript to introduce to you the most commonly used and practical regular expressions and their usage in WEB development. Regular expressions are a discipline and cannot be explained in one article. There are many theoretical things on the Internet. Students who are interested can search for a lot. However, you may not need to focus on learning regular expressions that you cannot figure out thoroughly. Look at this article and examples to present you with commonly used and practical regular expressions.
Common PHP expression usage:
1. Match positive integer: /^[1-9]\d*$/
2. Match non-negative integers (positive integer + 0): /^\d+$/
3. Match Chinese: /^[\x{4e00}-\x{9fa5}]+$/u
4. Match email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
5. Match URL: (((f|ht){1}(tp|tps)://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)
6. Match the beginning of the letter, 5-16 characters, alphanumeric underscore: /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
7. Match numbers, letters, underscores, Chinese: /^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+$/u
8. Match the Chinese postal code: /^[1-9]\d{5}$/
9. Match IP address: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/
10. Match the ID card of mainland China: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$/
Examples of PHP regular verification string methods:
$str = "Chinese";
$preg = "/^[\x{4e00}-\x{9fa5}]+$/u"; //Match Chinese
if(preg_match($preg,$str,$arr)){
$msg = 'Match was successful! ';
}else{
$msg = 'Match failed! ';
}
echo $msg;
Common Javascript expression usage
1. Match positive integer: /^[0-9]*[1-9][0-9]*$/
2. Match non-negative integers (positive integer + 0): /^\d+$/
3. Match Chinese: /^[\u4e00-\u9fa5]/
4. Match email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
5. Match URL: /^(f|ht){1}(tp|tps):\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?/
6. Match the beginning of the letter, 5-16 characters, alphanumeric underscore: /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
7. Match numbers, letters, underscores, Chinese: /^[\u4e00-\u9fa5A-Za-z0-9_]+$/
8. Match the Chinese postal code: /^[1-9]\d{5}$/
9. Match IP address: /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/
10. Match the ID card of mainland China: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}(\d|x|X)$/
Examples of Javascript regular verification string methods:
var str = "abc@";
var preg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; //Match Email
if((str)){
var msg = "Match successfully";
}else{
var msg = "Match failed!";
}
alert(msg);