🏡 Home

Regular Expressions Note 3: Match zero character or more times and lazy matching

Part of my posts on learning regular expressions

Match characters occured zero or more times

This trips me up. Matching character that occurede zero or more times using the star *.

const yes = 'yattaaaaaa!'
const goodbye  = 'tata'
const sheepSays = 'baba'

const taRegex = /ta*/gi

cconst yesResult = yes.match(taRegex)
console.log(yesResult) //will result ["t", "taaaaa"]

const goodbyeResults = goodbye.match(taRegex)
console.log(goodbyeResults) // will result ["ta", "ta"]

const sheepSaysResults = sheepSays.match(taRegex)
console.log(sheepSaysResults) // will result null

Find characters with Lazy Matching

Regex default to greedy matching for example

const span = "<span>this is element</span>"
const spanRegex = /<.*>/
const results = span.match(spanRegex)

console.log(results) // will return ["<span>this is element</span>"]

the results will return <span>this is element</span> because the regex will match the longest string.

If we want to match the shortest string we use question mark ?

const span = "<span>this is element</span>"
const spanRegex = /<.*?>/
const results = span.match(spanRegex)

console.log(results) // will return ["<span>"]