开发者

How do i write a regex for capturing decimal numbers?

开发者 https://www.devze.com 2023-03-06 11:41 出处:网络
I need to write a regex that will capture all of the following numbers f开发者_StackOverflow中文版rom a sample text:

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

精彩评论

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