I'm trying to translate a string and put an underscore before any uppercase character. The closest I have got is:
out=in.replaceAll("([^_])([A-Z])","$1_$2");
but with "ABCDEF" it returns "A_BC_DE_F", I guess because after considering "AB", it doesn't look at "BC" because "B" was already in the previous match. Of course I could apply it twice, but is there a more elegant solution?
There is also:
out=in.replaceAll("([A-Z])","_$1");
but it adds a leading "_".
Java 1.8, if that matters
You may put the [^_] negated character class into a non-consuming positive lookbehind
s = s.replaceAll("(?<=[^_])[A-Z]","_$0");
Note that there is no need to enclose the whole consuming pattern with capturing parentheses, $0 backreference stands for the whole match value.
See this Java demo:
System.out.println(
"ABCDEF".replaceAll("(?<=[^_])[A-Z]","_$0")
); // => A_B_C_D_E_F
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With