正则表达式匹配28个字符的ID字符串和特殊字符

时间:2015-08-02 17:04:30

标签: c# regex

我有一个小应用程序,读取其他应用程序生成的一些日志文件。在这些文件中,正在处理与此类似的行:

 ban added reason='Posting links to malware websites' cluid='oNNtrNGo6kdxNRshT8MiHlq4wR8=' bantime=0 by client 'Someone'(id:4)

目前我有一点Regex \w{27}=将获得该字符串中的流量值。流体总长度为27个字符,其中' ='在末尾。但是,其中一些ID在ID本身中有特殊字符,例如:IVz0tUZThCdbBnCWjf+axoMqVTM=(注意' +'字符)这意味着我的正则表达式与此不匹配ID。

我需要将哪些内容添加到正则表达式才能匹配ID'

1 个答案:

答案 0 :(得分:1)

你只对cluid的价值感兴趣(就在单引号之间)。你可以尝试这种模式:

"cluid='([^']{27}=)'"

它捕获了27个不是单引号的字符(假设单引号不能成为值的一部分),后跟等号到捕获组1。

示例:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string line1 = "ban added reason='Posting links to malware websites' cluid='oNNtrNGo6kdxNRshT8MiHlq4wR8=' bantime=0 by client 'Someone'(id:4)";
        Match m = Regex.Match(line1, "cluid='([^']{27}=)'");
        if (m.Success)
        {
            Console.WriteLine(m.Groups[1]);
        }

        string line2 = "ban added reason='Posting links to malware websites' cluid='IVz0tUZThCdbBnCWjf+axoMqVTM=' bantime=0 by client 'Someone'(id:4)";
        m = Regex.Match(line2, "cluid='([^']{27}=)'");
        if (m.Success)
        {
            Console.WriteLine(m.Groups[1]);
        }
    }
}

结果:

oNNtrNGo6kdxNRshT8MiHlq4wR8=
IVz0tUZThCdbBnCWjf+axoMqVTM=

Fiddle Demo