开发者

How to use variables with regex?

开发者 https://www.devze.com 2022-12-28 22:01 出处:网络
This is the input string: 23x^45*y or 2x^2 or y^4*x^3. I am matching ^[0-9]+ after letter x. In other words I am matching x followed by ^ followed by numbers. Problem is that I don\'t know that I am

This is the input string: 23x^45*y or 2x^2 or y^4*x^3.

I am matching ^[0-9]+ after letter x. In other words I am matching x followed by ^ followed by numbers. Problem is that I don't know that I am matching x, it could be any letter that I stored as variable in my char array.

For example:

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

I am new to regex and I new that this can be done if I 开发者_如何学编程define regex variables, but I don't know how.


You can use the pattern @"[cEle]\^\d+" which you can create dynamically from your 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 things to note:

  • It is necessary to escape the ^ inside the regular expression otherwise it has a special meaning "start of line".
  • It is a good idea to use Regex.Escape when inserting literal strings from a user into a regular expression, to avoid that any characters they type get misinterpreted as special characters.
  • This will also match the x from the end of variables with longer names like tax^2. This can be avoided by requiring a word boundary (\b).
  • If you write x^1 as just x then this regular expression will not match it. This can be fixed by using (\^\d+)?.


The easiest and faster way to implement from my point of view is the following:

Input: This?_isWhat?IWANT

        string tokenRef = "?";
        Regex pattern = new Regex($@"([^{tokenRef}\/>]+)");

The pattern should remove my tokenRef and storing the following output:

  • Group1 This
  • Group2 _isWhat
  • Group3 IWANT


Try using this pattern for capturing the 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

Do not forget to use the option IgnoreCase for matching, if required.

0

精彩评论

暂无评论...
验证码 换一张
取 消