[英]Regex get the text after the match which must be the last occurrence
我想在C#应用程序中使用正则表达式在最后一次出现“cn =”之后提取字符串。 所以我需要的是“cn =”和\\ character的最后一次出现之间的字符串请注意,源字符串可能包含空格。
例:
OU =公司\\ OU =国家\\ OU =网站\\ CN =办公\\ CN =名称\\ OU =宠物
结果:
名称
到目前为止,我已经(?<=cn=).*
用于选择cn =使用正向lookbehind后的文本和(?:.(?!cn=))+$
用于查找最后一次出现,但我不知道如何组合它一起来获得理想的结果。
您可以尝试使用以下正则表达式 ...
(?m)(?<=cn=)[\w\s]+(?=\\?(?:ou=)?[\w\s]*$)
看看正则表达式演示
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);
}
}
}
您可以使用否定前瞻:
cn=(?!.*cn=)([^\\]+)
小组$1
并在regex101.com上观看演示 。 作为完整的C#
代码,请参阅ideone.com上的演示 。
(?<=cn=)(?!.*cn=)([^\\\\]+)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.