Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ replace regex in all cases

Can a LINQ expression replace all cases where regex would have previously been used?

In other words; does a regex exist that can not be represented by a LINQ query?

like image 946
Maxim Gershkovich Avatar asked Dec 02 '22 02:12

Maxim Gershkovich


2 Answers

It's probably possible to craft a LINQ expression for any given regular expression, but doing so will likely be unreasonable in many cases. Even if you eliminate things like backreferences, regular expressions can be arbitrarily complex. The beauty of regular expressions (and I find it somewhat surprising that I use the term "beauty" to describe regex) is that it's a compact and expressive, but very narrowly focused tool for pattern matching in strings.

LINQ, on the other hand, is a very expressive general purpose tool.

Take a simple regular expression like (ab)+([0-9^%#@-.,]{1,5})ab[0-9]$. Can you write a LINQ expression for that? If you can, it's going to be quite verbose--certainly much more verbose than the regex, and you'll have to include code that gets the capture groups. Not only do you have to say if the string matches the expression, but you have to say where the match starts, how long it is, etc. I suspect it's possible, but you're going to write a whole lot of custom code to do it.

I'm not a huge fan of the regex, but it does have its place. Sometimes it really is the right tool for the job. I'd jump at the chance to replace it with something better, but LINQ sure isn't it.

like image 50
Jim Mischel Avatar answered Dec 27 '22 02:12

Jim Mischel


I have never thought that about LINQ in that way. Regex is a very comprehensive language for text matching, whereas LINQ is query language. LINQ does have predicates to do matching, but is not itself a text matching tool. I would not recommend using LINQ in place of Regex. What are your intentions in this case.

like image 36
hivie7510 Avatar answered Dec 27 '22 01:12

hivie7510