Is it only me? I am always scrambling to write regular expressions in one go and always have to look up on what all those symbols do. I am always looking for these stuffs online. Here you will find commonly used regular expression examples. Hope this list will help you all.
Regular Expression
Regular expression is used to describe a pattern of characters. It can match a part of string and can be used for advanced character matching and replacing. We can use preg_match function in PHP for comparing string with regular expression.
Meta characters
Meta characters are used to match specific type of character. Some examples of meta characters are listed below
| \d | any digit from 0 to 9 |
| \w | any character from a to z, A to Z and 0 to 9 |
| \s | any white space character (space, tab etc.) |
| ^ | starts with |
| $ | ends with |
| * | means zero or more |
| + | means one or more |
| . | match any single character be it letter, number, whitespace etc |
| \ | match meta character by escaping them |
| i | patterns are case sensitive. Adding i modifier after regular expression makes it case insensitive |
| [] | square bracket are used to denote character sets. It matches one of any of the characters in the bracket |
| [ – ] | hyphen specifies a range of characters eg: [0-9] … This matches a single digit between 0 and 9 |
Some examples of regular expressions
| Regular Expression | String | Matches? | Remarks |
| /abc/ | abc | Yes | matches literal abc |
| /abc/ | abczxv | Yes | String still contains abc |
| /abc/ | bcwz | No | Looking for literal abc which is not present in string |
| /10:20/ | 10:20:25 | Yes | |
| /ab\d/ | ab12 | Yes | \d matches number |
| /abc\d/ | ab12 | No | There is no c |
| /\d\d/ | ab12 | Yes | |
| /\w\s\d/ | ab 12 | Yes | |
| /^abc/ | abc | Yes | |
| /^abcxyz/ | abcxyz | Yes | |
| /^abc/ | 123abc | No | Doesn’t start with abc |
| /abc$/ | 123abc | Yes | |
| /^abc$/ | abc | Yes | |
| /^abc$/ | abcxyz | No | |
| /a*bc/ | abc | Yes | look for a repeated zero or more times |
| /a*bc/ | bc | Yes | |
| /a+bc/ | bc | No | pattern is looking for at least one a |
| /a+bc/ | aaaabc | Yes | |
| /ab.de/ | abcde | Yes | |
| /ab.de/ | ab4de | Yes | |
| /ab.de/ | ab de | Yes | |
| /ab.de/ | abde | No | |
| /abc.*/ | abcdef | Yes | .* any number of any character |
| /abc.*/ | abc | Yes | |
| /abc\./ | abc. | Yes | matches literal dot character |
| /abc/ | Abc | No | pattern are case sensitive |
| /abc/i | Abc | Yes | i modifier makes pattern case insensitive |
| /a[123]b/ | a2b | Yes | |
| /a[123]b/ | a3b | Yes | |
| /a[123]b/ | a4b | No | |
| /a[123]+b/ | a123233b | Yes | |
| /a[1-5]b/ | a2b | Yes | Matches character between 1 and 5 |
| /a[1-5]b/ | a8b | No | |
| /[a-z0-9 ]+/ | hello world | Yes | |
| /a[^123]b/ | a2b | No | ^ matches any one character except for the characters specified including ranges |
| /a[^123]b/ | a4b | Yes | |
| /[^a-z]+/ | hello | No | |
| /[^a-z]+/ | HELLO | Yes |
