Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 53
  • Last Modified:

Regular Expression Help

I need a regular expression that will identify  decimal values that are  less 3 digits in length..

For example:

1.0  --> Yes
2.00 --> Yes
0.01 -->  Yes
0.008 --> No
4  --> no
0
tmajor99
Asked:
tmajor99
  • 3
  • 3
  • 2
3 Solutions
 
TechieMDCommented:
^[0-9]*(?:\.[0-9]{1,2})?$

Open in new window

0
 
Jeff DarlingDeveloper AnalystCommented:
^\d{1,2}\.\d{1,2}$

Open in new window

0
 
TechieMDCommented:
Jeff, the regex you provided wouldn't allow for 111.0 which according to the question should be a valid match. A correction to mine though:
^[0-9]*\.[0-9]{1,2}$

Open in new window

As 4 should fail but 4.0 shouldn't.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Jeff DarlingDeveloper AnalystCommented:
The specs say "less 3 digits in length".  so 11.0 or 1.11 would match, but not 111.0 because that is 4 digits.  The question doesn't say, but I'm assuming that there won't be a number without a leading or trailing digit on the decimal.  so 0.01 for example and not just .01

I'm assuming 4 doesn't match because its not a decimal value.
0
 
Terry WoodsIT GuruCommented:
I'm assuming the following are invalid:
111.
.111
111

This isn't the most efficient pattern to run, but performance is not usually the problem with a regex (it's usually the correctness or edge cases that are a problem):
^(?=\d+\.\d+)(?!(\d.*){4}).*$

Open in new window


To help you adjust it if you need to:
(?=\d+\.\d+) is a lookahead that requires at least one digit before and after a decimal point
(?!(\d.*){4}) is a negative lookahead that invalidates any values with 4 or more digits
0
 
Terry WoodsIT GuruCommented:
Jeff, your pattern will match 11.11, which I understand is incorrect.
TechieMD, yours will match 111111.1 and also .1, which I understand is incorrect.
0
 
TechieMDCommented:
There is insufficient data from the examples in the question to extrapolate whether the asker wants to see only three digits in total or a maximum of two decimal places.

Waiting for asker clarification.
0
 
Jeff DarlingDeveloper AnalystCommented:
@Terry

Thanks, I missed that test case.  It wasn't listed.

^\d{1,1}\.\d{1,2}$|^\d{1,2}\.\d{1,1}$

Open in new window


If the correct spec is Zero leading or  trailing digits, then that would change the pattern.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now