Say, we’ve got to find a 3-digit number. With \d
that’s simple:
1 | showMatch( "I'm 100 years old" , /\d\d\d/ ) |
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.
1 | showMatch( "I'm 12345 years old" , /\d{5}/ ) |
To find 3-5 digit numbers, specify two numbers in figure brackets: \d{3,5}
1 | showMatch( "I'm 1234 years old" , /\d{3,5}/ ) |
It is possible to omit the last number. So, a number with 3 or more digits will be \d{3,}
:
1 | showMatch( "I'm 12345678 years old" , /\d{3,}/ ) |
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
.
1 | var re = /#[a-f0-9]{6}/gi |
3 | var subj = "color: #121212; background-color: #AA00ef \ |
4 | width: 12px; bad-colors: f#fddee #fd2 " |
6 | alert( subj.match(re) ) |
The problem with this solution is that is also finds color in longer sequences:
1 | alert( "#12345678" .match( /#[a-f0-9]{6}/gi ) ) |
If that’s an issue, it can be fixed by a more advanced regular expression.