DisgruntledGoat
DisgruntledGoat

Reputation: 72510

Why is my regex is not matching?

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?

Upvotes: 1

Views: 320

Answers (7)

serg
serg

Reputation: 111265

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

Upvotes: 1

Il-Bhima
Il-Bhima

Reputation: 10880

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

Upvotes: 0

TheJacobTaylor
TheJacobTaylor

Reputation: 4143

.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("==[^=]*==")

Upvotes: 0

Schildmeijer
Schildmeijer

Reputation: 20946

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

Upvotes: 0

Igor Artamonov
Igor Artamonov

Reputation: 35961

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

Upvotes: 0

sepp2k
sepp2k

Reputation: 370102

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

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

Upvotes: 4

Roman
Roman

Reputation: 66156

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

Upvotes: 7

Related Questions