Hello! Friends, there was a problem, I can not understand why the matches in the string are not counted. What could be the problem?

Task: Calculate how many emoticons in one line. Smilies can with such eyes: ":;" with nose: "-" and mouths: ")] ([" (mouths can be repeated)

static void Main(string[] args) { for (int i = 0; i < 5; i++) { string line = null; string pattern = @"^([:|;]{1}[-]*[)|(|[|\]]+)$"; Regex reg = new Regex(pattern, RegexOptions.IgnoreCase); Console.WriteLine("Введите строку на проверку корректности:"); line = Console.ReadLine(); MatchCollection mc = reg.Matches(line); foreach (Match mat in mc) { Console.WriteLine(mat.ToString()); } Console.WriteLine(mc.Count.ToString()); }//for }//main 
  • one
    Remove the beginning and end of the line - "([: |;]] {1} [-] * [) | (| [|]] +)" this should work. You can test it here regex101.com/r/Be3kmn/1 - koks_rs
  • Thank you buddy! - Vladislav Solopov

2 answers 2

Smilies can with such eyes: ":;" with nose: "-" and mouths: ")] ([" (mouths can be repeated)

In this case, [:|;] contains an extra | in character classes | is not an OR operator, but simply means a given character. In [)|(|[|\]] the same problem, although if you need to find :-| , then | it is better to leave it in a single copy. By the way, if ] put it in the character class immediately after the opening character [ , then ] needs to be escaped. {1} best removed from handwritten regularizers, because without a quantifier, any pattern finds exactly one match. [-] does not need to be escaped or enclosed in a character class, because outside a character class it - not a special metacharacter.

In addition to the above, the characters ^ / $ are anchors, they bind the pattern to the beginning and end of the line. Therefore, your regulars will find a string of type :-) , but will not find a string of type Нет :( . Remove them from the expression.

Use

 "[:;]-*[][()]+" 

See the demo (test regular expressions for .NET on sites that support its syntax, recess 101 does not support. NET).

The RegexOptions.IgnoreCase parameter is not needed here, there are no letters in the regular RegexOptions.IgnoreCase .

Code:

 static void Main(string[] args) { for (int i = 0; i < 5; i++) { string line = null; Regex reg = new Regex(@"[:;]-*[][()]+"); Console.WriteLine("Введите строку на проверку корректности:"); line = Console.ReadLine(); MatchCollection mc = reg.Matches(line); foreach (Match mat in mc) { Console.WriteLine(mat.ToString()); } Console.WriteLine(mc.Count.ToString()); } } 

    If you do not want to deal with Regex, you can more easily implement it. S-array of emoticons.

     private Int32 CountWords(string[] S, String S0) { string[] temp = S0.Split(S, StringSplitOptions.None); return temp.Length - 1; }