How to make an optional Regular Expression argument in C #

I have the following situation

I need to match something like

abc#(x,-12d)

or

abc#(x,-12d, 24d) etc.

This means that the last parameter is optional.

I have already done the regex and it works, but since I don’t know how to make it optional, from now on I use two different regExpression.

public static bool ValidFn(string input)
        {          
            string regEx1 = @"^[a-zA-Z]*#\([A-Za-z0-9]+,[-|+]?\d+[dwmqy],[-|+]?\d+[dwmqy]\)";
            string regEx2 = @"^[a-zA-Z]*#\([A-Za-z0-9]+,[-|+]?\d+[dwmqy]\)";
            Regex r1 = new Regex(regEx1);
            Regex r2 = new Regex(regEx2);
            Match m1 = r1.Match(input);
            Match m2 = r2.Match(input);
            if (m1.Success || m2.Success) return true;
            else return false;
        }

How can I make regExp1 as optional so that I can eliminate the use of regExp2.

thank

+3
source share
2 answers

The symbol ?in the regular expression means "Repeat 0 or 1 time." Therefore, he makes the statement optional.

You want to capture the last ", 24d" when it exists. Need to wrap what captures, "24d" with? character.

:

string regEx1 = @"^[a-zA-Z]*#\([A-Za-z0-9]+,[-|+]?\d+[dwmqy](,\s*[-|+]?\d+[dwmqy])?\)";

, \s* ,

+5

?, ? [-|+]?.

0

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


All Articles