I am trying to build a regex that will check to see if a string has a hyphen 0 or 1 times.
So it would return the following strings as ok.
1-5
1,3-5
1,3
The following would be wrong.
1-3-5
I have tried the following, but it is fine with 1-3-5:
([^-]?-){0,1}[^-]
In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.
A regular expression followed by an asterisk ( * ) matches zero or more occurrences of the regular expression. If there is any choice, the first matching string in a line is used.
The * quantifier matches the preceding element zero or more times. It's equivalent to the {0,} quantifier.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
This works:
^[^-]*-?[^-]*$
^^ ^ ^ ^
|| | | |
|| | | |-- Match the end of string
|| | |------- Match zero or more non-hyphen characters
|| |--------- Match zero or one hyphens
||-------------- Match zero or more non-hyphen characters
|--------------- Match the beginning of string
In this case, you need to specify matching the beginning (^
) and end ($
) of the input strings, so that you don't get multiple matches for a string like 1-3-5
.
Perhaps something simpler:
var hyphens = input.Count(cc => cc == '-');
Your regular expression works because it found the first instance of a hyphen, which meets your criteria. You could use the following regular expression, but it would not be ideal:
^[^-]*-?[^-]*$
If you have your strings in a collection, you could do this in one line of LINQ. It'll return a list of strings that have less than two hyphens in them.
var okStrings = allStrings.Where(s => s.Count(h => h == '-') < 2).ToList();
Judging by the way you've formatted the list of strings I assume you can't split on the comma because it's not a consistent delimiter. If you can then you can just using the String.Split
method to get each string and replace the allStrings
variable above with that array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With