Sidebar

Case Insensitive ReplaceAll

0 votes
1.0K views
asked Dec 3, 2015 by chris-m-8014 (760 points)

I have a code snippet that is intended to replace some data in a message that looks like this:

 

var value = message.getNode("PID-13.4");

value = value.replaceAll('NONE@EMAIL.COM', '');

message.setNode("PID-13.4", value);

 

It needs to be case insensitive.  Can I safely use this code?  value = value.replaceAll("?i"+'NONE@EMAIL.COM', '');

 

Is there a better way?

1 Answer

0 votes
 
Best answer

Here is a code sample that you can try in QIE:

var s = new java.lang.String("Hello HELLO heLLo HellO hellO hello \\r\\n\\.");
qie.debug(s.replaceAll("Hello", "NONE@EMAIL.COM"));
// qie.debug(s.replaceAll("?i" + "Hello", "NONE@EMAIL.COM"));
qie.debug(s.replaceAll("(?i)" + "Hello", "NONE@EMAIL.COM"));
qie.debug(s.replaceAll("(?i)" + java.util.regex.Pattern.quote("Hello"), "NONE@EMAIL.COM"));
qie.debug(s.replaceAll("(?i)" + "\\r\\n\\.", "Stuff"));
qie.debug(s.replaceAll("(?i)" + java.util.regex.Pattern.quote("\\r\\n\\."), "Stuff"));
Some things to note in the above snippet:
 
1. This only work on the Java String class of strings not JavaScript strings.  So, be sure to convert any JavaScript strings to Java String.
 
2. Wrap the ?i in parenthesis, like so: (?i).  If you uncomment the line without out it wrapped it, throws the following error:
 
WrappedException: Wrapped java.util.regex.PatternSyntaxException: Dangling meta character '?' near index 0
?iHello
 
3. Use Pattern.quote (if needed) to avoid the replacement string from being interpreted as a regex pattern (which may cause unexpected results).  Converts it to a string literal.  
See:
 
Which states:
"This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern"
answered Dec 4, 2015 by rich-c-2789 (16,630 points)
selected Dec 4, 2015 by chris-m-8014
commented Dec 4, 2015 by rich-c-2789 (16,630 points)
Other than the above gotchas, it is likely the simplest solution (least number of lines of code).
...