Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - How to use variables with regex?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ().
  • If you write x^1 as just x then this regular expression will not match it. This can be fixed by using (^d+)?.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...