Search engine performance in C # regular expressions. Should I avoid them if I can?

all! I'm brand new to regular expressions, but I like them, LOT!

Call me nitpicky if you want, but I really would like to know if I should avoid using lookaheads and lookbehinds if I have an option.

For example, both of the following commands do the same thing, one uses lookbehind, and the other does not.

the_str = Regex.Replace(the_str, @"(;|!|\?) \.{3}", "$1...");

the_str = Regex.Replace(the_str, @"(?<=(;|!|\?)) \.{3}", "...");

Which one would you use? Which is more efficient?

Thank you for your responses!

+3
source share
1 answer

I tested both locally and the method using lookbehind was about 25% slower.

, lookahead lookbehind, 10% :

s = Regex.Replace(s, @"(;|!|\?) (?=\.{3})", "$1");

, , . , , . , , , .

, "blah; ... foo ...; bar bar ? ..." 1000 , 100 .

0.944s   No lookarounds    Regex.Replace(s, @"(;|!|\?) \.{3}", "$1...") 
1.027s   Look ahead        Regex.Replace(s, @"(;|!|\?) (?=\.{3})", "$1")
1.210s   Look behind       Regex.Replace(s, @"(?<=(;|!|\?)) \.{3}", "...")
1.124s   Both              Regex.Replace(s, @"(?<=(;|!|\?)) (?=\.{3})", "")
+5

Source: https://habr.com/ru/post/1767244/


All Articles