Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Extract a number from a string
Supposing a string has only one number you need to extract, /\d+/ should do it:
'Test 123123329'.match(/\d+/)
// Array [ "123123329" ]
Match an email address
A simplistic approach is to check non-space characters before and after the @ sign, using \S:
/(\S+)@(\S+)\.(\S+)/
/(\S+)@(\S+)\.(\S+)/.exec('copesc@gmail.com')
//["copesc@gmail.com", "copesc", "gmail", "com"]
This is a simplistic example however, as many invalid emails are still satisfied by this regex.
Capture text between double quotes
Suppose you have a string that contains something in double quotes, and you want to extract that content.
The best way to do so is by using a capturing group, because we know the match starts and ends with ", and we can easily target it, but we also want to remove those quotes from our result.
We’ll find what we need in result[1]:
const hello = 'Hello "nice flower"'
const result = /"([^"]*)"/.exec(hello)
//Array [ "\"nice flower\"", "nice flower" ]
Get the content inside an HTML tag
For example, get the content inside a span tag, allowing any number of attributes inside the tag:
/<span\b[^>]*>(.*?)<\/span>/
/<span\b[^>]*>(.*?)<\/span>/.exec('test')
// null
/<span\b[^>]*>(.*?)<\/span>/.exec('<span>test</span>')
// ["<span>test</span>", "test"]
/<span\b[^>]*>(.*?)<\/span>/.exec('<span class="x">test</span>')
// ["<span class="x">test</span>", "test"] Lessons in this unit:
| 0: | Introduction |
| 1: | Introduction |
| 2: | Anchoring |
| 3: | Match Items in Ranges |
| 4: | Matching a Range Item Multiple Times |
| 5: | Negating a Pattern |
| 6: | Meta Characters |
| 7: | Regular Expressions Choices |
| 8: | Quantifiers |
| 9: | Optional Items |
| 10: | Groups |
| 11: | Capturing Groups |
| 12: | Using match and exec Without Groups |
| 13: | Noncapturing Groups |
| 14: | Flags |
| 15: | Inspecting a Regex |
| 16: | Escaping |
| 17: | String Boundaries |
| 18: | Replacing |
| 19: | Greediness |
| 20: | Lookaheads |
| 21: | Lookbehinds |
| 22: | Unicode |
| 23: | Unicode Property Escapes |
| 24: | ▶︎ Examples |