How do I use variables with regex?

This line of input: 23x^45*y or 2x^2 or y^4*x^3

.

I match ^[0-9]+

after the letter x

. In other words, I am matching x

and then ^

followed by numbers. The problem is I don't know what I am matching x

, it could be any letter that I have stored as a variable in my char array.

For instance:

foreach (char cEle in myarray) // cEle is letter in char array x, y, z, ...
{
    match CEle in regex(input) //PSEUDOCODE
}

      

I'm new to regex and I know it can be done if I define regex variables, but I don't know how.

+2


a source to share


2 answers


You can use a template @"[cEle]\^\d+"

that can be dynamically created from a character array:

string s = "23x^45*y or 2x^2 or y^4*x^3";
char[] letters = { 'e', 'x', 'L' };
string regex = string.Format(@"[{0}]\^\d+",
    Regex.Escape(new string(letters)));
foreach (Match match in Regex.Matches(s, regex))
    Console.WriteLine(match);

      

Result:



x^45
x^2
x^3

      

A few notes:

  • Must be avoided ^

    within a regex, otherwise it has the special meaning "start of line".
  • It is recommended to use Regex.Escape

    when inserting literal strings from a user into a regex to avoid any characters they print from being misinterpreted as special characters.
  • This will also match x from the end of variables with longer names like tax^2

    . This can be avoided if a word boundary ( \b

    ) is required .
  • If you write x^1

    once x

    , this regex won't match. This can be fixed using (\^\d+)?

    .
+3


a source


Try this pattern to capture a number, but excluding the x ^ prefix:

(?<=x\^)[0-9]+

string strInput = "23x^45*y or 2x^2 or y^4*x^3";
foreach (Match match in Regex.Matches(strInput, @"(?<=x\^)[0-9]+"))
    Console.WriteLine(match);

      



This should print:

45
2
3

      

Remember to use the IgnoreCase

match option if required.

0


a source







All Articles