Say, we’ve got to find a 3-digit number. With \d
that’s simple:
showMatch( "I'm 100 years old", /\d\d\d/ ) // 100
But let’s go a step further. What if we want to search for 5-digit numbers. Should we repeat \d
5 times: \d\d\d\d\d
?
Luckily, there is a better way.
Character count can be specified using {n}
syntax. So, \d{5}
means 5 digits, same as \d\d\d\d\d
.
The example below finds a 5-digit number.
showMatch( "I'm 12345 years old", /\d{5}/ ) // "12345"
To find 3-5 digit numbers, specify two numbers in figure brackets: \d{3,5}
showMatch( "I'm 1234 years old", /\d{3,5}/ ) // "1234"
It is possible to omit the last number. So, a number with 3 or more digits will be \d{3,}
:
showMatch( "I'm 12345678 years old", /\d{3,}/ ) // "12345678"
Write a regexp to find a CSS-color, which starts with '#'
and contains exactly 6 hexadimal chars (only this kind of colors in this task).
var re = /*...your global regexp...*/ var subj = "color: #121212; background-color: #AA00ef \ width: 12px; bad-colors: f#fddee #fd2 " alert( subj.match(re) ) // #121212,#AA00ef
The color should Write a regexp to describe a web-color, which starts with # followed by 6 hexadimal chars.
A hexadimal character is [0-9a-fA-F]
. Here we can use case-insensitive match and shorten the expression to [0-9a-f]
.
To repeat it 6 times, use the quantifier {6}
.
Finally, gives us /#[a-f0-9]{6}/gi
.
var re = /#[a-f0-9]{6}/gi var subj = "color: #121212; background-color: #AA00ef \ width: 12px; bad-colors: f#fddee #fd2 " alert( subj.match(re) ) // #121212,#AA00ef
The problem with this solution is that is also finds color in longer sequences:
alert( "#12345678".match( /#[a-f0-9]{6}/gi ) ) // #12345678
If that’s an issue, it can be fixed by a more advanced regular expression.