如何在正则表达式中使用变量? [英] How to use variables with regex?

查看:344
本文介绍了如何在正则表达式中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是输入字符串: 23x ^ 45 * y或2x ^ 2或y ^ 4 * x ^ 3

我在字母 x 后匹配 ^ [0-9] + 。换句话说,我匹配的是 x ,然后是 ^ ,然后是数字。问题是我不知道我是否匹配 x ,它可能是我作为变量存储在char数组中的任何字母。

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.

例如:

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

我是regex的新手,并且我新定义了我可以通过定义regex变量来完成此操作,但是我不知道如何做。

I am new to regex and I new that this can be done if I define regex variables, but I don't know how.

推荐答案

您可以使用模式 @ [cEle] \ ^ \d + 字符数组:

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);

结果:

x^45
x^2
x^3

A需要注意的几件事:

A few things to note:


  • 有必要将常规中的 ^ 转义

  • 插入文字时使用 Regex.Escape 是个好主意。从用户到正则表达式的字符串,以避免他们键入的任何字符被误解为特殊字符。

  • 这也将匹配长名称(如<$)的变量末尾的x c $ c> tax ^ 2 。可以通过使用单词边界( \b )来避免。

  • 如果您写 x ^ 1 就像 x 一样,则此正则表达式将不匹配它。可以使用(\ ^ \d +)?来解决。

  • 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+)?.

这篇关于如何在正则表达式中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆