1

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?

Community
  • 1
  • 1
ylun.ca
  • 2,504
  • 7
  • 26
  • 47
  • the \ must be escaped – fferri Jun 15 '15 at 21:07
  • Somebody posted the correct solution, and deleted it as I was commenting on it. Whoever it was, it was correct, so please re-post! – ylun.ca Jun 15 '15 at 21:07
  • @mescalinum why must the \ be escaped? I thought that \ itself was an escaping character, so that when you do \\[, it would escape the [? If I do \\\[, wouldn't it actually be matching \\[? – ylun.ca Jun 15 '15 at 21:09
  • 1
    You have to escape the \ as \\ in a Java literal string, so that the regex parser then interprets it as \\[ (which means a literal [ ) – aryn.galadar Jun 15 '15 at 21:14
  • Wow, okay yea that actually makes sense. Is this language dependent? I believe SO's regex guide doesn't do this, which was confusing me. @aryn.galadar – ylun.ca Jun 15 '15 at 21:18
  • @ylun.ca I also saw that correct solution. I guess suggestion was to use double '\\' instead of single '\' in your current regex. – apgp88 Jun 15 '15 at 21:18
  • 1
    Yes, double-escape is a Java thing - the regular expression itself should just be a single \, but Java treats the \ character as an escape character as well, so you have to double it. – aryn.galadar Jun 15 '15 at 21:19
  • Thank you, would you like to post an answer? Since the other person seemingly decided to change their mind about answering @aryn.galadar. – ylun.ca Jun 15 '15 at 21:22
  • 1
    @apgp88 Yes that suggestion worked in my script. And the reason was as aryn stated – ylun.ca Jun 15 '15 at 21:22

1 Answers1

1

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:

"(^\\[)|(\\]$)"
aryn.galadar
  • 716
  • 4
  • 13