vaibhav
vaibhav

Reputation: 4103

Regex issue removes \n while parsing

There is an existing regex in my code which is [^\s"']+|"[^"]*"|'[^']*'. My problem is that when i do something like:

Matcher matcher = regex.matcher("INDIA \n PAKISTAN");
  StringBuilder returnQuery = new StringBuilder();
  while (matcher.find()) {
      String str = matcher.group();
      if (AND.equalsIgnoreCase(str) || OR.equalsIgnoreCase(str) || NOT.equalsIgnoreCase(str)) {
          returnQuery.append(str.toUpperCase()).append(" ");
      } else {
          returnQuery.append(str).append(" ");
      }
  }

it removed the \n characters as well which i want to retain, Can someone please suggesta solution.

Appreciate the help in advance

Vaibhav

Upvotes: 1

Views: 102

Answers (1)

FailedDev
FailedDev

Reputation: 26940

The \s metacharacter is used to find a whitespace character. A whitespace character can be:

  • A space character
  • A tab character
  • A carriage return character
  • A new line character
  • A vertical tab character
  • A form feed character

So you if you are using \s you are out of luck. Just use a character class without \n e.g.

[ \r\t]

This way your \n will be retained.

Upvotes: 5

Related Questions