简体   繁体   中英

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

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}[^-]

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.

You could approach it this way:

string StringToSearch = "1-3-5";
MatchCollection matches = Regex.Matches("-", StringToSearch);
if(matches.Count == 0 || matches.Count == 1)
{
  //...
}

I just tested your expression and it appears to give the result you want. It break 1-3-5 into {1-3} and {-5}

http://regexpal.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM