ylun
ylun

Reputation: 2534

How to pattern match [ and ] in Java?

The string is something in the format:

[anything anything]

with a space separating the two, 'anything's.

I've tried:

(string).replaceAll("(^[)|(]$)","");

(string).replaceAll("(^\[)|(\]$)","");

but the latter gives me a compilation error and the first doesn't do anything. I implemented my current solution based on:

Java Regex to remove start/end single quotes but leave inside quotes

Looking around SO yields me many questions that answer problems similar to mine but implementing their solutions do not work (they either do nothing, or yield compilation errors):

regex - match brackets but exclude them from results

Regular Expressions on Punctuation

What am I doing wrong?

Upvotes: 1

Views: 103

Answers (1)

aryn.galadar
aryn.galadar

Reputation: 735

Since both Java and regex treats the \ character as an escape character, you actually have to double them when using in a Java literal string. So the regular expression:

(^\[)|(\]$)

in a Java string actually should be:

"(^\\[)|(\\]$)"

Upvotes: 1

Related Questions