Regular expressions are a powerful tool for matching patterns in strings. Here are a few common regular expressions that are useful in programming:
\d
: This matches any digit (0-9).\w
: This matches any word character (a-z, A-Z, 0-9, _).\s
: This matches any whitespace character (space, tab, newline)..
: This matches any character except for a newline.*
: This matches zero or more of the preceding character or group.+
: This matches one or more of the preceding character or group.?
: This matches zero or one of the preceding character or group.^
: This matches the start of a string.$
: This matches the end of a string.{n}
: This matches exactly n of the preceding character or group.{n,}
: This matches n or more of the preceding character or group.{n,m}
: This matches at least n and at most m of the preceding character or group.
Here are a few examples of regular expressions that are commonly used in programming:
- Validation:
- Email address:
/^[a-zA-Z0-9.!#$%&'*+/=?^_{|}~-]+@a-zA-Z0-9?(?:.a-zA-Z0-9?)*$/`
- Phone number:
/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/`
- Parsing:
- Extracting URLs from a piece of text:
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&\/\/=]*)/`
- Extracting IP addresses:
/\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/`
These are just a few examples, and the specific regular expression that you’ll need will depend on the task you’re trying to accomplish. It’s a good idea to become familiar with the full range of options available to you when working with regular expressions in your programming projects.