. | Matches any single character except newline | “h.t” matches “hat”, “hot”, “hit” |
* | Matches zero or more occurrences of the previous character | “a*b” matches “b”, “ab”, “aab”, “aaab” |
+ | Matches one or more occurrences of the previous character | “a+b” matches “ab”, “aab”, “aaab”, but not “b” |
? | Matches zero or one occurrence of the previous character | “colou?r” matches “color” and “colour” |
^ | Matches the start of a line | “^Hello” matches “Hello World” but not “World Hello” |
$ | Matches the end of a line | “World$” matches “Hello World” but not “World Hello” |
[ ] | Matches any single character in brackets | “[aeiou]” matches any vowel |
[^ ] | Matches any single character not in brackets | “[^aeiou]” matches any consonant |
( ) | Groups characters | “(ab)+” matches “ab”, “abab”, “ababab” |
| | Alternation (OR) | “cat|dog” matches “cat” or “dog” |
{ } | Specifies exact number of occurrences to match | “a{3}” matches exactly three “a”s |
\d | Matches any digit | “\d{3}” matches three digits |
\D | Matches any non-digit | “\D+” matches one or more non-digits |
\w | Matches any word character (a-z, A-Z, 0-9, _) | “\w+” matches one or more word characters |
\W | Matches any non-word character | “\W” matches any single non-word character |
\s | Matches any whitespace character | “\s” matches space, tab, newline |
\S | Matches any non-whitespace character | “\S+” matches one or more non-whitespace characters |
\b | Matches a word boundary | “\bword\b” matches “word” as a whole word |
\B | Matches a non-word boundary | “\Bword\B” matches “word” only if it’s part of a larger word |
(?i) | Makes the match case-insensitive | “(?i)hello” matches “hello”, “Hello”, “HELLO” |
(?m) | Enables multiline mode | “(?m)^start” matches “start” at the beginning of any line |
(?s) | Enables single-line mode (dot matches newline) | “(?s).*” matches everything including newlines |
(?<name>…) | Named capturing group | “(?<year>\d{4})” captures a year in a named group |
(?:…) | Non-capturing group | “(?:ab)+” matches “ab”, “abab” without creating a capture group |
(?=…) | Positive lookahead | “Jacob(?=\sSm)” matches “Jacob” only if followed by ” Sm” |
(?!…) | Negative lookahead | “Jacob(?!\sSm)” matches “Jacob” only if not followed by ” Sm” |
(?<=…) | Positive lookbehind | “(?<=Mr.)\s\w+” matches a name if preceded by “Mr.” |
(?<!…) | Negative lookbehind | “(?<!Mr.)\s\w+” matches a name if not preceded by “Mr.” |
Leave a Reply
Want to join the discussion?Feel free to contribute!