1

I have some lines in a text file like this:

==Text==

I'm trying to match the start, using this:

line.matches("^==[^=]")

However, this returns false for every line... little help?

DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
  • What language is this in? If it's Java, pretty sure it tries to match the entire line. This would fail, because the [^=] would eventually not match, making the entire line not match, returning false – Tarka Feb 22 '10 at 22:02

7 Answers7

7

As I remember, method matches() searches for exact match only.

Roman
  • 64,384
  • 92
  • 238
  • 332
  • This is true, and the documentation could be a lot clearer about it -- http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html – mob Feb 22 '10 at 22:09
4

matches automatically anchors the regex, so the regex has to match the whole string. Try:

line.matches("==[^=].*")
sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

You can also use String.startsWith("=="); if it is something simple.

serg
  • 109,619
  • 77
  • 317
  • 330
0
try line.matches("^==[^=]*==$")
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
Schildmeijer
  • 20,702
  • 12
  • 62
  • 79
0

Try with line.matches("^==(.+?)==\\s*$")

Igor Artamonov
  • 35,450
  • 10
  • 82
  • 113
0

.matches only returns true if the entire line matches. In your case, the line would have to start with '==' and contain exactly one character that was not equals. If you are looking to match that string for the whole line:

line.matches("==[^=]*==")

TheJacobTaylor
  • 4,063
  • 1
  • 21
  • 23
0

If I remember correctly, matches will only return true if the entire line matches the regex. In your case it won't. To use matches you will need to extend your regex (using wildcards) to match to the end of the line. Alternatively you could just use Matcher.find() method to match substrings of the line

Il-Bhima
  • 10,744
  • 1
  • 47
  • 51