Search code examples
javaregexreplaceall

Java: Replace all non-digit symbols except symbol "+" on the first position


I`d like to format inputed strings over such rule: replace all non-digit symbols except first position in the string: it should be only digit or symbol '+'.

I use regexp functionality

private static final String REGEXP_NOT_DIGITS = "[^\\+0-9]";

String result = sample.replaceAll(REGEXP_NOT_DIGITS, "");

But the result of this replacement is string with digits and '+' symbols at any position. Please, help me to clarify my condition that I would replace all '+' symbol except only 1 position in the line.

Edit. Right now output is:

sample[0] sample = 0123456789; result = 0123456789 expected:0123456789

sample[1] sample = +380+380+380+; result = +380+380+380+ expected:+380380380

sample[2] sample = dd0 11 22 33 44 55; result = 01122334455 expected:01122334455

sample[3] sample = +380-456(789); result = +380456789 expected:+380456789

sample[4] sample = d3+580 456 789; result = 3+580456789 expected:3580456789

sample[5] sample = +380456789; result = +380456789 expected:+380456789

Everything is Ok except having symbol '+' inside string


Solution

  • You can use:

    String result = sample.replaceAll("(?!^)\\+|[^+\\d]+", "");
    

    RegEx Demo

    (?!^)\\+ is a negative lookahead that will match + everywhere except at line start.