Spacing consecutive characters in string with Java regex

xenoid :

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

Wiktor Stribiżew :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=110761&siteId=1