Resurrecting this question because it had a simple regex solution that wasn't mentioned. (Found your question while doing some research for a regex bounty quest.)
'[^']*'|(_)
The left side of the alternation matches complete 'single quoted strings'
. We will ignore these matches. The right side matches and captures underscores to Group 1, and we know they are the right underscores because they were not matched by the expression on the left.
Here is working code (see online demo):
import java.util.*;
import java.io.*;
import java.util.regex.*;
import java.util.List;
class Program {
public static void main (String[] args) throws java.lang.Exception {
String subject = "code_numbers = '123_456'";
Pattern regex = Pattern.compile("'[^']*'|(_)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
if(m.group(1) != null) m.appendReplacement(b, " ");
else m.appendReplacement(b, m.group(0));
}
m.appendTail(b);
String replaced = b.toString();
System.out.println(replaced);
} // end main
} // end Program
Reference
- How to match pattern except in situations s1, s2, s3
- How to match a pattern unless...