PRD
PRD

Reputation: 29

Insert spaces into a string with certain pattern JAVA

I have a String input which looks smth like this:

a = "-5+++5"  ---> -5 +++ 5
b = "5                 ++    -5" ---> 5 ++ -5
c = "ABC        */ ZXC" ---> ABC */ ZXC 
d = "-XY**          XX" ---> -XY ** XX

essentialy string consists from 3 parts: part1, part2 - integer or letters, probably with minus. and operation - some substring made of + - * / I need to insert spaces around operation thing, so i will be able to get an List with split(" ") My code is but it doesnt work(((

    string.replaceAll("(-?\\d+|\\D+)(?=[+\\-*/]+)", "$0 ");

and to get rid of exstra whitespaces

    string.replaceAll("\\s+", " ").trim()

Upvotes: 1

Views: 56

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You can use

^(-?\w+)\s*((?:(?!-\b)[/*+-])+)\s*(-?\w+)$

See the regex demo. Details:

  • ^ - start of string
  • (-?\w+) - Group 1 ($1): an optional - and then one or more word chars (\p{Alnum}+ might be a better idea if you need to exclude _)
  • \s* - zero or more whitespaces
  • ((?:(?!-\b)[/*+-])+) - Group 2 ($2): one or more /, *, +, - chars but the - char cannot be followed with a word char
  • \s* - zero or more whitespaces
  • (-?\w+) - Group 3 ($3): an optional - and then one or more word chars (or \p{Alnum}+)
  • $ - end of string

In Java:

String result = text.replaceFirst("^(-?\\w+)\\s*((?:(?!-\\b)[/*+-])+)\\s*(-?\\w+)$", "$1 $2 $3");

Upvotes: 1

Related Questions