Wednesday, May 31, 2017

MVEL and string splitting, what's up ?

I had to create an mvel function the other day that required some splitting and it was driving me nuts.  If I splitted with a "," (comma), it worked fine, but when it splitted with a "|" (pipe), it was funny business.  Other issues if you want to split on a "." (dot).

So what's going on ?




String[]values = delimited.split("|"); => works, but splitting each char


it resulted in chopping the string in individual characters.

Same with a dot.

String[]values = delimited.split("."); => error 

Finally I realized what was going on, the split functionality is actually based on RegEx, and since the "|" or "." are actual RegEx characters, I needed to escape it for the RegEx to work.  So I went with :

String[]values = delimited.split("\|");
and
String[]values = delimited.split("\.");

But now, I got an error too.

So here's the deal.  In RegEx, the escaping was done, but now we have an MVEL issue, as the "\" (backslash) is a special character in MVEL, so you need to escape that one too.  So I finally got it working with :


String[]values = delimited.split("\\|");
String[]values = delimited.split("\\.");

PS : if you want to join, => use String.join(delimiter, array)

String a = "aaaaaaa.bbbbbb.cccccc";
String[] b = a.split("\\.");
String.join("_",b); 

Will give you => aaaaaaa_bbbbbb_cccccc

No comments :

Post a Comment