0

I have trouble finding a regex matching this pattern:

  • A numeric (decimal separator can be . or ,), followed by
  • a dash -, followed by
  • a numeric (decimal separator can be . or ,), followed by
  • a semi-column or a space character

This pattern can be repeated one or more time.

The following examples should match the regex:

1-2;
1-2;3-4;5-6;
1,0-2;
1.0-2;
1,0-2.0;
1-2 3-4;
1-2 3,00-4;5.0-6;

The following examples should not match the regex:

1-2
1 2;
1_2;
1-2;3-4
4
  • You are aware of the conditional operator (a|b) right? Commented Sep 30, 2011 at 16:12
  • @Peter I wasn't. It could help a lot :) Commented Sep 30, 2011 at 16:13
  • 1
    1 2; appears in both the list of items that should match and the list of items that shouldn't match. Commented Sep 30, 2011 at 16:17
  • @Utensil Again a mistake from me! I should read what I wrote. Thanks! Commented Sep 30, 2011 at 16:19

2 Answers 2

2

Edit updated based on moving of 1 2; to non-match.


This should work:

@"^(\d+([,.]\d+)?-\d+([,.]\d+)?[ ;])+(?<=;)$"

Explanation

^              //Start of the string.
(              //Start of group to be repeated. You can also use (?=
\d+            //One or more digits.
([,.]\d+)?     //With an optional decimal
-              //Separated by a dash
\d+([,.]\d+)?  //Same as before.
[ ;]           //Terminated by a semi-colon or a space
)+             //One or more of these groups.
(?<=;)         //The last char before the end needs to be a semi-colon
$              //End of string.
Sign up to request clarification or add additional context in comments.

4 Comments

Looks good, except I don't think space is an alternative to dash, looks like it can only be used in place of a semicolon.
You don't have to escape the . inside brackets
@IAbs Thanks, I always forget about that. Fixed now.
Thanks that works. I updated my question after your answer so it does not quite answer it now, but I managed to adapt it: @"^([0-9]+([,.][0-9]+)?[-][0-9]+([,.][0-9]+)?[ ;])+(?<=;)$"
1

Try this:

@"^([\d.,]+-[\d.,]+[ ;])*[\d.,]+-[\d.,]+;$"

Note that [\d.,]+ accepts some character sequences which wouldn't normally be considered valid "numeric" values such as 00..,.,. You might want to find a better regular expression to match numeric values and substitute it into the regular expression.

1 Comment

+1 @Joey But this is a little better: (0|[1-9]\d*) otherwise, it won't accept 10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.