Regex for matching hyphens in a string 0 or 1 times

I am trying to create a regular expression that checks if a string has a hyphen 0 or 1 time.

This way it will return the following lines in order.

1-5 1,3-5 1,3 

The following is incorrect:

 1-3-5 

I tried the following, but this is normal from 1-3-5:

 ([^-]?-){0,1}[^-] 
+4
source share
5 answers

It 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 the coincidence of the beginning ( ^ ) and end ( $ ) of the input lines so that you do not get multiple matches for a string of type 1-3-5 .

+9
source

Maybe something simpler:

 var hyphens = input.Count(cc => cc == '-'); 

Your regular expression works because it has detected the first hyphen that matches your criteria. You can use the following regular expression, but it will not be ideal:

 ^[^-]*-?[^-]*$ 
+5
source

If you have rows in the collection, you can do this on a single LINQ line. It will return a list of lines with less than two hyphens.

 var okStrings = allStrings.Where(s => s.Count(h => h == '-') < 2).ToList(); 

Judging by how you formatted the list of strings, I assume that you cannot break the comma because it is not a sequential separator. If you can, you can simply use the String.Split method to get each row and replace the variable allStrings above with this array.

+1
source

You can approach like this:

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

I just checked your expression and it seems to give the result you want. It splits 1-3-5 into {1-3} and {-5}

http://regexpal.com/

-2
source

Source: https://habr.com/ru/post/1486662/


All Articles