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

  • You may consider following regex based solution for your task:

    final Pattern QRX = Pattern.compile("'[^']*'|([^']+)");
    
    String s = "Rule2 = if(event = 'Veteran''s Day', 'Day 1', 'Day 2', Measure1.Lag)";
    s = QRX.matcher(s).replaceAll(m ->
       m.group(1) != null ? m.group().replace(" ", "").toUpperCase() : m.group()
    );
    System.out.println(s);
    //=> RULE2=IF(EVENT='Veteran''s Day','Day 1','Day 2',MEASURE1.LAG)
    

    Regex pattern '[^']*'|([^']+) matches either a single quoted string or any 1+ characters that doesn't contain a ' in the 1st capture group.

    Code Demo