Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a hyphen in a string 0 or 1 times

Tags:

c#

regex

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}[^-]
like image 668
g.t.w.d Avatar asked Jun 17 '13 17:06

g.t.w.d


People also ask

How do you match a hyphen in RegEx?

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.

Is used for zero or more occurrences in RegEx?

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.

Which character is used to match zero or one times?

The * quantifier matches the preceding element zero or more times. It's equivalent to the {0,} quantifier.

What does '$' mean in RegEx?

$ 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.


3 Answers

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.

like image 140
FishBasketGordo Avatar answered Nov 09 '22 15:11

FishBasketGordo


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:

^[^-]*-?[^-]*$
like image 31
user7116 Avatar answered Nov 09 '22 14:11

user7116


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.

like image 37
keyboardP Avatar answered Nov 09 '22 16:11

keyboardP