There is a pattern

string mask = @"?????;8595??????;4501*;7005*;7701*;800???????;1505???"; 

And there is an input string

 string number = "70050045"; 

It is necessary to determine whether this string matches the pattern. The pattern and string are taken as an example. Use regex? But how to convert a pattern? Or is there some other way to compare? Thank.

Closed due to the fact that the essence of the issue is incomprehensible to the participants Vadim Ovchinnikov , αλεχολυτ , Denis Bubnov , fori1ton , aleksandr barakin Jan 27 '17 at 15:49 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    What do the symbols in your template mean? Specify the rules of interpretation. - VladD

1 answer 1

Suppose yours ? means "any number ", * means "zero or more numbers",; means "or." In this case, your mask is easy to turn into a regular expression.

 string mask = @"?????;8595??????;4501*;7005*;7701*;800???????;1505???"; string processedMask = "^(" + // исключаем сопоставление в середине mask.Replace(';', '|') // ; == или .Replace("?", "\\d") // ? == одна цифра .Replace("*", "\\d*") // * == ноль или больше цифр + ")$"; // исключаем сопоставление в середине var regex = new Regex(processedMask); 

Now it's easy to check:

 string number = "70050045"; bool isGood = regex.IsMatch(number); 
  • Thanks for the answer! Exactly what is needed! I almost did: mask.Replace (";", "$ |"). Replace ("?", "[0-9]"). Replace ("*", "([0-9] *) ") +" $ "; Only used static Regex.IsMatch (); there is no difference? - Daria
  • @Daria: Well, if you plan to use the regular schedule very often, you can create a Regex with RegexOptions.Compiled , it will be faster due to the additional memory consumption. - VladD
  • @Daria: And in your version there is no ^ , so it should take lines like "whatever11111117005" . - VladD
  • one
    Yes, now I use this option: "^" + mask.Replace (";", "$ | ^"). Replace ("?", "[0-9]"). Replace ("*", "([ 0-9] *) ") +" $ ". Those. add ^ and | for each option, and not just for the entire line in general. - Daria