正则表达式获取匹配后的文本,该文本必须是最后一次出现

pan*_*mic 5 c# regex

我想在 C# 应用程序中使用正则表达式最后一次出现“cn=”后提取字符串。所以我需要的是最后一次出现“cn=”和\字符之间的字符串请注意源字符串可能包含空格。

例子:

ou=company\ou=country\ou=site\cn=office\cn=name\ou=pet

结果:

姓名

到目前为止,我已经(?<=cn=).*使用正向后视来选择 cn= 之后的文本并(?:.(?!cn=))+$找到最后一次出现,但我不知道如何将它组合在一起以获得所需的结果。

m87*_*m87 4

您可以尝试使用以下正则表达式...

(?m)(?<=cn=)[\w\s]+(?=\\?(?:ou=)?[\w\s]*$)
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示

C#演示

using System;
using System.Text.RegularExpressions;

public class RegEx
{
    public static void Main()
    {
        string pattern = @"(?m)(?<=cn=)[\w\s]+(?=\\?(?:ou=)?[\w\s]*$)";
        string input = @"ou=company\ou=country\ou=site\cn=office\cn=name\ou=pet";

        foreach (Match m in Regex.Matches(input, pattern))
        {
            Console.WriteLine("{0}", m.Value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)