Text

Regex Tutorial for Beginners: Learn Regular Expressions with Examples

A complete regex tutorial for beginners. Learn how to use regular expressions for pattern matching, text search, and data validation with practical examples.

WebUtil Team

What is a Regular Expression?

A regular expression (regex) is a sequence of characters that defines a search pattern. Regex is used for pattern matching in strings — finding, replacing, and validating text. Every programming language supports regex in some form: JavaScript has RegExp, Python has re module, Go has regexp package, and bash has grep/sed/awk. Regex syntax is standardized across languages with minor differences. Our Regex Tester lets you experiment with patterns in real-time.

Regex Basic Syntax: Characters and Anchors

Literal characters match themselves: /hello/ matches 'hello' in any string. The dot . matches any single character except newline. Anchors ^ and $ match the start and end of a string (or line with multiline flag). Word boundary \b matches between a word character and non-word character. Examples: /^hello/ matches 'hello' only at the start, /world$/ matches 'world' only at the end, /\bword\b/ matches the exact word 'word' but not 'sword' or 'words'.

Character Classes and Quantifiers

Character classes let you match sets of characters: [aeiou] matches any vowel, [a-z] matches any lowercase letter, [0-9] matches any digit. Negated classes use ^ inside brackets: [^0-9] matches any non-digit. Predefined classes include \d (digit), \w (word char), \s (whitespace). Quantifiers control repetition: * (zero or more), + (one or more), ? (zero or one), {3} (exactly 3), {2,4} (2 to 4). Example: /\d{3}-\d{4}/ matches phone-like patterns like '555-1234'.

Sponsored
Advertisement

Groups, Capturing, and Alternation

Parentheses () create capturing groups that extract matched substrings: /(\w+)@(\w+)\.(\w+)/ captures email parts. Non-capturing groups (?:...) group without capturing. Alternation | matches one of several patterns: /cat|dog|bird/ matches any of the three words. Backreferences like \1 reference captured groups within the pattern. Named groups (?<name>...) make patterns self-documenting. Example: /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/ extracts date components.

Practical Regex Examples and Use Cases

Email validation: /^[\w.-]+@[\w.-]+\.\w{2,}$/. URL matching: /https?:\/\/[\w.-]+(?:\/[\w.-]*)*\/?/. Phone numbers: /^\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/. Password strength: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\w\s]).{8,}$/ requires uppercase, lowercase, digit, and special character. IP addresses: /^(?:\d{1,3}\.){3}\d{1,3}$/. Use our Regex Tester to build and test your patterns interactively.

Use our free online tool to get started instantly.