Alisa Alisa - 5 days ago 5
Java Question

java regex to replace any single character with space

I want to remove any single character (including single characters at the beginning or end of string).
For example,

String s = "I am testing regex. This'll print results for A B c d ^ * ( ) { } [ ] done .";
System.out.println(s);


should print:

am testing regex. This'll print results for done





I tried:

s = s.replaceAll("(\\s+.(?=\\s))", " ");


which gives me:

I am testing regex. This'll print results for done .


I want to remove the beginning and ending single characters as well in the same regular expression.

Answer

You may use

.replaceAll("(?s)(?<!\\S).(?!\\S)", " ")

or

.replaceAll("(?<!\\S)[^ ](?!\\S)", " ")

and, perhaps, use trim() on the result. See the regex demo.

Details:

  • (?s) - a DOTALL embedded flag option (so that . could match any character including line break symbols)
  • (?<!\S) - a negative lookbehind requiring either start of string or a whitespace before the current location
  • . - (the consuming part) any single char (if it must be anything but space, use [^ ])
  • (?!\S) - a negative lookahead that requires either the end of string or a whitespace immediately to the right of the current location.

Note that you may further adjust the consuming part as needed. If you only need to match non-whitespace chars, replace . with \S.

Comments