Understanding Regex: The Simplest Guide.
Source: Dev.to
What is Regex?
- A pattern‑matching tool used to find, replace, validate, or extract specific patterns in a string.
- Common uses: finding numbers, validating emails, filtering alphabets, removing special characters, extracting dates, phone numbers, IDs, etc.
Regex Syntax in JavaScript
In JavaScript a regex is written between slashes:
/pattern/flags
Example
/[0-9]+/g
Breakdown
| Part | Meaning |
|---|---|
/ | Regex starts |
[0-9]+ | Pattern (one or more digits) |
/ | Regex ends |
g | Flag – global (find all matches) |
Character Sets
The most important part of regex is the character set ([ ]). Whatever you put inside the brackets will match any one of those characters.
| Pattern | Meaning |
|---|---|
[0-9] | Any digit |
[a-z] | Lower‑case letters a‑z |
[A-Z] | Upper‑case letters A‑Z |
[a-zA-Z] | Any alphabetic character |
[0-9-] | Digit or hyphen |
Tip: Mastering these five patterns gives you roughly 60 % of what you need to know.
Quantifiers
Quantifiers decide how many times a pattern should repeat.
| Symbol | Meaning | Example | Explanation |
|---|---|---|---|
+ | 1 or more | [0-9]+ | One or more digits |
* | 0 or more | a* | “a” may or may not exist |
? | 0 or 1 | colou?r | Matches “color” or “colour” |
Anchors
Anchors specify the position of a match within the string.
| Anchor | Meaning |
|---|---|
^ | String starts with |
$ | String ends with |
Example
/^[0-9]+/
→ The string must start with a number.
Flags
Flags come after the closing slash and modify the regex’s behavior.
| Flag | Name | Use |
|---|---|---|
g | Global | Find all matches |
i | Ignore case | Case‑insensitive matching |
m | Multiline | Applies to each line |
s | Dotall | . also matches newline |
Example
/hello/gi
Matches: hello, Hello, HELLO, hElLo, etc.
Real‑World Practical Examples
1. Remove Numbers
"50-200 metric tonnes".replace(/[0-9]/g, "");
// Output: "-metric tonnes"
2. Extract Numbers (including hyphen)
"50-200 metric tonnes".match(/[0-9-]+/)[0];
// Output: "50-200"
3. Validate Email
/^[\w.-]+@[\w.-]+\.\w{2,}$/i.test("user@example.com");
// Returns: true
4. Keep Only Letters, Numbers, and Spaces
text.replace(/[^a-zA-Z0-9 ]/g, "");
// Removes all other characters
5. Manual Filtering (without regex)
let result = "";
for (let ch of str) {
if (!"0123456789".includes(ch)) {
result += ch;
}
}
Summary – Key Rules to Remember
- Character set
[ ]– what to match - Quantifiers
+ * ?– how many times - Anchors
^ $– start / end of the string - Flags
g i m s– modify behavior
If you keep these rules in mind, regex becomes easy to use.
What You Can Do with Regex
- Clean strings
- Validate user input
- Extract data
- Perform replacements efficiently
Regex = Pattern + Repetition + Flags
Master this formula and regex will feel simple forever. 🚀