So you can use replaceAll("(.)\\s", "$1")
Example:
String s = "S O M E T E X T I W O U L D L I K E T O H I G H L I G H T";
s = s.replaceAll("(.)\\s", "$1");
System.out.println(s);
Output: SOME TEXT I WOULD LIKE TO HIGHLIGHT
Explanation:
Think of your text as two characters chunks (I will mark them with ^^
and ##
).
S O M E T E X T
^^##^^##^^##^^##
If you look closely you will notice that you want to remove second character from each pair (which is space), and leave first character:
S O M E T E X T
^ # ^ # ^ # ^ # T - T will not be affected (will stay)
because it doesn't have space after it.
You can achieve it with (.)\s
regex where
.
represents any character (including space)
\s
represents any whitespace
This way first character will be placed in group (indexed as 1
) which allows us to use match from this part in replacement part via $x
where x
represents group index.
Ver.2 (in case spaces to remove are not only on odd indexed positions)
Other way to solve this problem is to remove only these spaces which
are placed right after non-space character (?<=\\S)\\s
S O M E T E X T
^ ^ ^ ^ ^ ^ ^
are placed before other spaces \\s(?=\\s)
S O M E T E X T
^ ^ ^ ^##### ^ ^ ^
This way as you can see one space is left (the one right before word) so your solution can look like
s = s.replaceAll("(?<=\\S)\\s|\\s+(?=\\s)", "");