As you all know, in ColdFusion, when you want to do a find or replace with no case sensitivity, you just append "NoCase" to the method call. We have all used:
As you well know (if you follow my blog), I am a huge fan of using the Java String methods for regular expression find and manipulation. The problem with that though is that there is no "NoCase" type methods built into the Java string (except for String::equalsIgnoreCase(), but that doesn't use regular expressions). I thought the only way to work around this was to either put all characters in regular expression (ie [a-zA-Z]), but it turns out there is a flag for performing a case-insensitive search:
How did I miss that? I have been doing regular expressions for a long time now and this one has escaped me. Crazy! But, it's so awesome. You just put the flag (?i) in your regular expression and everything to the right of it will be case-insensitive:
<!--- Set string value. ---> <cfset strText = "Libby is FUNNY" /> <!--- Check case-sensitive match. ---> #strText.Matches( "[a-z ]+" )# <!--- Check case-INsensitive match. ---> #strText.Matches( "(?i)[a-z ]+" )#
The first method outputs NO... the second method outputs YES. How freakin' cool is that. You can even perform case insensitive sub-strings:
<!--- Only allow case-INsensitivity on LIBBY and FUNNY. ---> #strText.Matches( "(?i:libby)[a-z ]+(?i:funny)" )#
This also outputs YES.
So anyway, that's pretty freakin' cool! I don't know how I missed that when learning Regular Expressions, but now that I know, it is sooo on.
Oh, and just be careful. This is only for JAVA regular expressions. If you try to use this type of notation in ColdFusion method calls, it will throw an error:
Malformed regular expression "(?i:libby)[a-z ]+(?i:funny)". Reason: Sequence (?:...) not recognized.
... Just another reason I am huge fan of using the underlying Java methods.
Want to use code from this post? Check out the license.