开发者

I can't get this simple regex to work correctly

I'm doing this in Javascript

Here's my string: 09.22.2011-23.21-west-day

Here's what I'd like to pull out of it: 23.21

Here's my expression: /-[0-9]*\.[0-9]*/

I get -23.21 so I'd have to run a a replace method after this to remove the "-". Is there a way to leave out the "-" with this regex or not? I never really perfected my regex skills because I usually use PHP whic开发者_运维问答h has the nice () capture groups.


Javascript has capture groups too:

var time = "09.22.2011-23.21-west-day".match(/-(\d{2}\.\d{2})/)[1]

Gives you 23.21

  1. You can use \d as a shorthand for [0-9]
  2. If you know how many digits it's supposed to have, use {n} or {m,n} quantifiers. It will reduce the chance of it matching the wrong thing.


You can use () in JavaScript too!

s = '09.22.2011-23.21-west-day';
rx = s.match('-([0-9]*\.[0-9]*)')
alert(rx[1]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜