0

What could be the regular expression to match below String

String str = "<Element>\r\n <Sub>regular</Sub></Element>";

There is a

carriage return "\r", new line character "\n" and a space after <Element>.

My code is as below

if(str.matches("<Element>([\\s])<Sub>(.*)"))
{
     System.out.println("Matches");
}
Suvasis
  • 1,431
  • 1
  • 24
  • 40

1 Answers1

1

Use the "dot matches newline" switch:

if (str.matches("(?s)<Element>\\s*<Sub>(.*)"))

With the switch turned on, \s will match newline characters.

I slso fixed your regex, removing two sets of redundant brackets, and adding the crucial * after the whitespace regex.

Bohemian
  • 365,064
  • 84
  • 522
  • 658
  • @Bohemain : As I mentioned, I have already tried using ([\\s]) is to match newline and carriage return. It does not work. – Suvasis Apr 02 '13 at 06:49
  • @Suvasis You tried with `[\\s]`, but you didn't provide a cardinality. In your regex, replace `[\\s]` by `\\s+` or `\\s*` (brackets are useless in this case). – sp00m Apr 02 '13 at 07:21