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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.