Regex matches string after colon

The input line looks something like this: OU = TEST: This001. We need an extra "This001". Best in C #.

+6
c # regex
source share
4 answers

What about:

/OU=.*?:(.*)/ 

Here's how it works:

 OU= // Must contain OU= . // Any character * // Repeated but not mandatory ? // Ungreedy (lazy) (Don't try to match everything) : // Match the colon ( // Start to capture a group . // Any character * // Repeated but not mandatory ) // End of the group 

For / they are delimiters to know where the regular expression starts and where it ends (and to add parameters).

The captured group will contain This001 .

But that would be faster with a simple Substring() .

 yourString.Substring(yourString.IndexOf(":")+1); 

Resources:

+29
source share

"OU =" smells like you do an Active Directory or LDAP search and respond to the results. While regex is a brilliant tool, I just wanted to make sure that you also know the excellent System.DirectoryServices.Protocols classes that were created to parse, filter, and manipulate just such data.

SearchResult, SearchResultEntry, and DirectoryAttribute, in particular, will be the friends you might be looking for. I have no doubt that you can use a regex or substring as good as the next guy, but it's also nice to have another good tool in the toolbar.

Have you tried these classes?

+5
source share

Solution without regex:

 var str = "OU=TEST:This00:1"; var result = str.Split(new char[] { ':' }, 2)[1]; // result == This00:1 

Regex vs Split vs IndexOf

Split

 var str = "OU=TEST:This00:1"; var sw = new Stopwatch(); sw.Start(); var result = str.Split(new char[] { ':' }, 2)[1]; sw.Stop(); // sw.ElapsedTicks == 15 

Regex

 var str = "OU=TEST:This00:1"; var sw = new Stopwatch(); sw.Start(); var result = (new Regex(":(.*)", RegexOptions.Compiled)).Match(str).Groups[1]; sw.Stop(); // sw.ElapsedTicks == 7000 (Compiled) 

Indexoff

 var str = "OU=TEST:This00:1"; var sw = new Stopwatch(); sw.Start(); var result = str.Substring(str.IndexOf(":") + 1); sw.Stop(); // sw.ElapsedTicks == 40 

Winner: Divide

References

+3
source share

if OU=TEST: is your requirement before the string you want to match, use this regex:

 (?<=OU\s*=\s*TEST\s*:\s*).* 

that the regular expression matches any length of text after the colon, while any text before the colon is only a requirement.

You can replace TEST with [A-Za-z]+ to match any type other than TEST, or replace TEST with [\w]+ to match any length of any combination of alphabet and numbers.

\s* means that it can be any number of spaces or nothing in this position, remove it if you do not need such a check.

0
source share

All Articles