C # regular expressions

I know that there are many questions about regular expressions, but they all seem to be one problem than general use. I also have a problem how to solve. I tried to learn by reading about regular expressions, but it gets complicated. Here is my question:

WITH#

I need to check two text fields that exist in the same form. The math operations that I encoded can handle any floating point number. For this particular application, I know three formats in which there will be numbers, or there is an error in the username. I would like to prevent these errors in the example if the extra number is accidentally entered or if the input is too early, etc.

Here are the formats: "#. ####" "##. ####" "###. ##", where "#" is a required number. Formats starting with a single or two-digit integer must have 4 lagging digits or more. I closed it at 8, or so I tried lol. A format starting with a three-digit integer should never have more than two digits following the decimal point.

Here is what I have tried so far.

    Regex acceptedInputRegex = new Regex(@"^\b[0-9]{3}.[0-9]{2}|[0-9]{1,2}.[0-9]{4,8}$");

    Regex acceptedInputRegex = new Regex(@"^\b\d{3}.\d{2} | \d{1,2}.\d{4,8}$");

I tried this, thinking that the match was what I wanted to achieve, and as if matching with my negative expression means there is a problem. In both attempts, I was unsuccessful. This is the code:

    if (acceptedInputRegex.IsMatch(txtMyTextBox1.Text) || acceptedInputRegex.IsMatch(txtMyTextBox2.Text))
            {

            } else
            {
                MessageBox.Show("Numbers are not in the right format", "Invalid Input!");
                return;
            }
  • Are regular expressions what I should use to solve this problem?
  • If not, please tell me what you recommend. If so, please help me fix my regular expression.

Thank.

+4
1

, , ^ $ :

@"^(?:\d{3}\.\d{2}|\d{1,2}\.\d{4,8})$"

regex.

  • ^ -
  • (?: - , :
    • \d{3}\.\d{2} - 3 , . 2
    • | -
    • \d{1,2}\.\d{4,8} - 1 2 , ., 4 8
  • ) - ,
  • $ - .

\d ASCII-, RegexOptions.ECMAScript:

var isValid = Regex.IsMatch(s, @"^(?:\d{3}\.\d{2}|\d{1,2}\.\d{4,8})$", RegexOptions.ECMAScript);
+4

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


All Articles