C#Regex获取特定字符后的值,但需要检查主要字符

时间:2018-06-01 19:49:57

标签: c# regex

我想为以下场景创建正则表达式

name like %name - 匹配并提取%名称

name like '%name' - 不应该与它有匹配'在%

之前

name like ' %name' - 不应该匹配以前的字符是' (忽略空间)

name like%name匹配并提取%name

这就是我得到的[^']%\ w +但是这个过去的两个案例已经覆盖

1 个答案:

答案 0 :(得分:2)

这可能符合您的需求,但它取决于前缀为name like的字符串。

void Main()
{
    var strings = new string[] {"name like %name", "name like '%name'", "name like ' %name'", "name like%name"};
    var regex = new Regex("^name like ?(%\\w+)");
    foreach (var item in strings)
    {
        Console.WriteLine($"string: \"{item}\" matches: {regex.IsMatch(item)} extracted: {(regex.Match(item).Groups.Count > 0 ? regex.Match(item).Groups[1].Value : string.Empty)}");
    }
    //Output:
    //string: "name like %name" matches: True extracted: %name
    //string: "name like '%name'" matches: False extracted: 
    //string: "name like ' %name'" matches: False extracted: 
    //string: "name like%name" matches: True extracted: %name
}

正则表达式分解为:

^name like:以name like

开头的字符串

?:可选空格

(%\\w+):我们的匹配组,挑选[a-zA-Z_]前缀为%

的任意数量的字符