开发者

How do i write a regex for capturing decimal numbers?

I need to write a regex that will capture all of the following numbers f开发者_StackOverflow中文版rom a sample text:

2.5
5
0.2
.5

Assuming its not going to be more than 2 digits on either side of the decimal point, what regex do i use?

thanks.


This should work.

(\d*\.?\d+)

It means

  • ( begin capture group
  • \d* any digit zero or more times
  • \.? a period zero or one times (i.e. it is optional)
  • \d+ any digit one ore more times
  • ) end capture group

It will match all the number you listed and capture them in $1.


This regex will do the job (i.e. no more than 2 digits on either side of the decimal point)

^(?:\d{0,2}\.\d{1,2})$|^\d{1,2}$

explanation:

^               # Begining of the string
  (?:           # begining of NON capture group
    \d{0,2}     # matches 0,1 or 2 digits
    \.          # decimal point
    \d{1,2}     # 1 or 2 digits
  )             # end of non capture group
$               # end of string

|               # OR

^               # Begining of the string
  \d{1,2}     # 1 or 2 digits
$               # end of string

This regex will match: 2.5, 5, 0.2, .5 but not: 123.456, 256


Take a look at this: http://www.regular-expressions.info/floatingpoint.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜