javastring

Change toUpperCase() all except those within single quotes


Over the last couple of days I have read through many similar questions but none that actually answers what I am looking for. Hence , posting this question.

I have a string, for example:

    String myString = "Rule2 = if(event = 'Veteran''s Day', 'Day 1', 'Day 2', Measure1.Lag)"; 

I want this to be changed to the following:

    myString = "RULE2=IF(EVENT='Veteran''s Day','Day 1','Day 2', MEASURE1.LAG)";

That is all text except those within single quotes are trimmed of extra spaces and turned to upperCase().

I thought I could use regex to extract [Rule2,if,event] and use String.replaceAll() et al. No luck. It is the third day today. My head has stopped working now. Please help.

Would be grateful for any pointers.


Solution

  • Here I use a a pattern for '...' or '... or non-apostrophes. Then that replaceAll will work, alternating uppercasing parts.

    Pattern pattern = Pattern.compile("('[^']*('|$)|[^']+)");
    String myString = "Rule2 = if(event = 'Veteran''s Day', 'Day1', 'Day2')";
    Matcher m = pattern.matcher(myString);
    String s = m.replaceAll(mr -> mr.group().startsWith("'")
                                  ? mr.group() : mr.group().toUpperCase());
    

    Shorter would be '.*?' but this is clear and does not clash with an odd number of apostrophes