Radioactive
Radioactive

Reputation: 769

Replace each underscore with a X

Use Case :

Input : "___Test_String"

Output: "XXXTest_String"

I would want to replace all the starting underscores with X. The catch being each underscore should be replaced with a respective X.

Conditions:

The string may or may not start with an underscore. If it does not start with an underscore, it stays as is.

I tried:

replaceAll("[_]","X")  = XXXTestXString - It replaced all the underscores.
replaceAll("^[_]+","X") = XTestXString - Replaced all the starting underscores with a single X.
replaceFirst("_","X") = X__Test_String - Just replaced the first underscore.

I know this is very easy to accomplish using a non-regex way, but I would want a regexp solution if possible.

Any help would be appreciated.

Upvotes: 0

Views: 102

Answers (1)

Andreas
Andreas

Reputation: 159106

You can do it using replaceAll("\\G_", "X").

The \G matcher means "The end of the previous match", which of course implies "The beginning of the input" on the first match. See javadoc of Pattern. See also Regular-Expressions.info.

The regex will keep matching as long as there is an underscore immediately following the previous match. It will match one underscore at a time, so each underscore is individually replaced with an X.

Once it finds the first non-underscore, matching ends, so the embedded underscore between t and S will not be matched.

Upvotes: 3

Related Questions