0

I have a textbox which should accept input in the following format:

[decimal], [decimal]; [decimal], [decimal]; [decimal], [decimal]

For example:

0.01,0.10; 0.20,0.50; 1.00,3.00; 4.00,1000.00

My knowledge of regular expression is very poor. I was able to do that much

^([0-9]+(\.[0-9]+))?$

But couldn't do much more. So any help will be greatly appreciated. Thanks.

Max
  • 12,622
  • 16
  • 73
  • 101
Mdb
  • 8,338
  • 22
  • 63
  • 98

5 Answers5

1

This pattern will match decimal strings:

^([0-9]+(\.[0-9]+))?$

However, it will not only match a single decimal and will not allow any other characters before or after it. Also, the decimal group is optional, so it allows the entire string empty.

To modify this string to match your input try this:

^(([0-9]+(?:\.[0-9]+)?),\s*([0-9]+(?:\.[0-9]+)?)(;\s*|$)){4}$
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • Hello, this is almost correct. But it allows the user to enter only half of the sequence. For example, entering: 0.01,0.10; is also acceptable. I need the user to always have to enter the four pairs of decimals. – Mdb Feb 05 '14 at 09:05
  • @Mdb Sorry, you question was a bit confusing because in the fist example you had 3 pairs and in the second you had 4. You can make it work for *n* pairs by replacing the `+` at the end with `{n}`. See my updated answer. – p.s.w.g Feb 05 '14 at 15:46
1

You regular expression can be like (you may have to adjust the spaces as it's not completely clear from your example where they are correct)

Also, the expression will depend on whether the semicolon at the end is:

optional:

^(\s?[0-9]+\.[0-9]+,[0-9]+\.[0-9]+;){3}(\s?[0-9]+\.[0-9]+,[0-9]+\.[0-9]+;?)$

shouldn't be there:

^(\s?[0-9]+\.[0-9]+,[0-9]+\.[0-9]+;){3}(\s?[0-9]+\.[0-9]+,[0-9]+\.[0-9]+)$

required:

^(\s?[0-9]+\.[0-9]+,[0-9]+\.[0-9]+;){4}
Szymon
  • 42,577
  • 16
  • 96
  • 114
0

Try to use this:

(\d+\.\d+,\d+\.\d+;?)\s*
Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
0

Below regex definition will match all decimal numbers with ; and , seperator, also deal with end decimal with no seperator

((?<DecimalNumber>[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?)([;,]*))

Use for loop in C# for capturing multiple values for the same group

Tyrant
  • 106
  • 2
  • 3
0

If you want it to be very strict and exactly match your example:

^(\d+\.\d+\,\d+\.\d+;\s){3}(\d+\.\d+\,\d+\.\d+\s*)

If it can be more loose and allow white-spaces:

^(\s*\d+\.\d+\s*\,\s*\d+\.\d+\s*;\s*){3}(\s*\d+\s*\.\d+\s*\,\s*\d+\.\d+\s*)

This last one also matches

0.01, 0.10;  0.20,   0.50; 1.00 ,3.00; 4.00  ,1000.00
Skiphan
  • 31
  • 3