-1

The following piece of code returns false when I believe it should return true. Can anyone tell me why? It's using java.util.regex.Pattern to parse the regex.

Pattern.compile("^\|:\|$".matcher("|   |").matches();
revo
  • 47,783
  • 14
  • 74
  • 117
Patrick
  • 77
  • 1
  • 3
  • 9

1 Answers1

2

A \ in a string literal must be escaped as \\.

If you want to match anything in between, use .*, not :.

When you use the matches method in Java, you don't need to add the string boundaries ^ and $ as this function returns true only when it matches the whole string.

You seem to want

Pattern.compile("\\|.*\\|").matcher("| |").matches();
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758