user2065207
user2065207

Reputation: 13

matching { regular expression java

I am new to regular expressions (and to java), so this is probably a simple question. I am trying to match the character { at the end of a line. My attempts are simply this:

row.matches("{$")

row.matches("\{$")

But both just give

Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition

What am I doing wrong?

Upvotes: 1

Views: 173

Answers (4)

Chris Forrence
Chris Forrence

Reputation: 10104

row.matches("^.*\\{$");

You simply need to escape the {, since it's a metacharacter. Because Java reserves a single backslash for special contexts (\n, \r, etc.), two backslashes are required to generate one backslash for the Pattern. Therefore,

\\{

will properly evaluate to

\{

Not only this, but the matches method checks to see iff the entire string matches, instead of just a subset. Hence, the ^.* part

Upvotes: 4

Simulant
Simulant

Reputation: 20122

you need to escape the { with an \ but to prevent that the \{ is read as special character (like \n for line-feed) you need to escape also the \ with an additional \ resulting to:

row.matches("\\{$");

Upvotes: 2

Arun Manivannan
Arun Manivannan

Reputation: 4313

Did escaping the angle bracket work?

as in \\{$

Tried it against

hello world{
    whatever{
    hello{dontmatch
    }
}

It matched world{ and whatever{ but not hello{dontmatch

Upvotes: 2

Grambot
Grambot

Reputation: 4524

You must escape the { character as it is a special char for regex

row.matches("\\{$")

Upvotes: 2

Related Questions