3

Is there anyway to use LIKE operator in VB.NET as case sensitive or insensitive during runtime? For example use a flag to do case sensitive or insensitive comparisons.

Obviously this can be done by simple converting them into lower case and forcing application to Option Compare Binary but maybe there is a better way to do this?

2 Answers 2

2

I don't think so. However, you should probably not use the Like operator anyways if case-insensitivity is important - instead, use regular expressions.

Dim re As New System.Text.RegularExpressions.Regex("^.+ough$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) re.IsMatch("rough") ' True re.IsMatch("tough") ' True re.IsMatch("rOUGH") ' True re.IsMatch("ough") ' False 

There's a lot to learn, but basically . is equivalent to ?, .* is equivalent to *, and \d is equivalent to #. You have to wrap it in ^ and $ for equivalency, too. Regular expressions are much more powerful and will do what you need.

You should probably add Imports System.Text.RegularExpressions if you plan to use them a lot. They can be compiled and reused for efficiency, too.

Sign up to request clarification or add additional context in comments.

7 Comments

That's the problem I don't need much powerful, I need less powerful :)
@dr. evil: Can you give us an example of the pattern in question, and in what situation it will be used?
It'll be entered by user as normal users can't write regex it'll be quite dirty to convert their wildcards into regex, still doable though.
@dr. evil: Not really; I found an article online that talks about using Like in C#, and you can apply the same principles. Just make the replacements of *, ?, and #, escape the whole thing, and surround it in ^ and $. It does sound complicated, but here's a pre-made one for you (and if you can't read C#, there's an online conversion tool too): social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/…
@minitech Yes that's the approach but I guess you also know that LIKE syntax is not just * and ?
|
0

You could provide a custom class to ensure that you get case case-insensitive comparison even if the default settings is Compare Binary(case sensitive). You can specify the Option Compare in a code-file:

Option Compare Text Public Class CaseInsensitiveLikeOperator Public Shared Function IsLike(str As String, pattern As String) As Boolean Return str Like pattern End Function End Class 

Now this works:

Dim isSame = CaseInsensitiveLikeOperator.IsLike("foo", "Fo?") ' True 

If your default is Option Compare Text you could provide two classes to be on the safe side.

Maybe the best option is to learn regex ;-)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.