Search code examples
javaregexwhitespace

Whitespace Matching Regex - Java


The Java API for regular expressions states that \s will match whitespace. So the regex \\s\\s should match two spaces.

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);
while (matcher.find()) matcher.replaceAll(" ");

The aim of this is to replace all instances of two consecutive whitespace with a single space. However this does not actually work.

Am I having a grave misunderstanding of regexes or the term "whitespace"?


Solution

  • Yeah, you need to grab the result of matcher.replaceAll():

    String result = matcher.replaceAll(" ");
    System.out.println(result);