Search code examples
javaandroidsplitreplaceall

Replace multiple non-digit char to 1 non-digit char


I am working on app that read weight value from weighing indicator. The output from the indicator are contains with symbols, non digit char and also a number. I just want to extract the number. I have already turn non-digits and symbols into several pipes using regex \D. Then I wanted to turn this string

||||||||||1234||||||||||||||1234||||||||||||||1234||||||||||||||1234||||||||||||||1234||||

into

|1234|1234|1234|1234

How could I possibly do that?


Solution

  • You could try a regex replacement:

    String input = "||||||||||1234||||||||||||||1234||||||||||||||1234||||||||||||||1234||||||||||||||1234||||";
    String output = input.replaceAll("\\|+", "|").replaceAll("\\|$", "");
    System.out.println(output);  // |1234|1234|1234|1234|1234