April 16, 2012

regex to allow decimals, but no commas

Question by Rookieatthis

I need a regex expression that allows decimals but no commas. Such as:
The expression is used in a validation to make sure people put in a price as a number, but no commas. I currently have a regex that allows for commas, numbers, and decimals, but I cannot seem to get the commas out.

This is the current regex that I have which doesnt allow commas or decimals, but I want decimals in there

/^[0-9 ]+$/,

Thanks for your help.

Answer by npinti

Something like this should work: ^d+(.d{2})?$

This basically states the following:

  • ^d+: Start from the beginning of the string (^) and match one or more digits (d+).
  • (.d{2})?: Match a period character (.) followed by exactly 2 digits (d{2}). The question mark denotes that the value within the brackets can either exist or not, meaning that it will match either 1 or 0 instances of the pattern.
  • $: The string must end here.

Answer by Starx

To match the currency you can use this regex


Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!