I want to extract the string after the last occurrence of "cn=" using regex in C# application. So what I need is the string between last occurence of "cn=" and \ character Please note that the source string may contains spaces.
Example:
ou=company\ou=country\ou=site\cn=office\cn=name\ou=pet
Result:
name
So far Ive got (?<=cn=).*
for selecting the text after the cn= using positive lookbehind and (?:.(?!cn=))+$
for finding the last occurence but I dont know how to combine it together to get desired result.
?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).
The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
Using regex \B-\B matches - between the word color - coded . Using \b-\b on the other hand matches the - in nine-digit and pass-key .
You may try using the following regex ...
(?m)(?<=cn=)[\w\s]+(?=\\?(?:ou=)?[\w\s]*$)
see regex demo
C# ( demo )
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);
}
}
}
You could use a negative lookahead:
cn=(?!.*cn=)([^\\]+)
Take group $1
and see a demo on regex101.com. As full C#
code, see a demo on ideone.com.
(?<=cn=)(?!.*cn=)([^\\]+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With