正则表达式

Numeric Quantifiers

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/ )  // 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.

1 showMatch( "I'm 12345 years old"/\d{5}/ )  //  "12345"

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}/ )  // "1234"

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,}/ ) // "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).

1 var re = /*...your global regexp...*/
2  
3 var subj = "color: #121212; background-color: #AA00ef \
4   width: 12px; bad-colors: f#fddee #fd2 "
5  
6 alert( subj.match(re) )  // #121212,#AA00ef

Solution

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
2  
3 var subj = "color: #121212; background-color: #AA00ef \
4   width: 12px; bad-colors: f#fddee #fd2 "
5  
6 alert( subj.match(re) )  // #121212,#AA00ef

The problem with this solution is that is also finds color in longer sequences:

1 alert( "#12345678".match( /#[a-f0-9]{6}/gi ) ) // #12345678

If that’s an issue, it can be fixed by a more advanced regular expression.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值