0

I have a text with variables like [abcderere].
In order to detect those variables i decided to create the following regex :

(\[.+?\])

It does work with string like [azerty][qwerty] but I want my regex to also detect String like [[azerty] because it matches the pattern but it doesn't work

HamZa
  • 13,530
  • 11
  • 51
  • 70
Romain G
  • 53
  • 7
  • Your regex seems to match strings like "[[azerty]" as is. Tested it here: http://www.regexplanet.com/advanced/java/index.html and in java itself. Are you using Pattern.compile("(\\[.+?\\])"); ? – Benjamin Gruenbaum Apr 25 '12 at 08:40
  • 5
    *"My question is pretty simple"* "What is the meaning of life?" Is also a simple question, it is the answer that is tricky. The simplicity of a question is unrelated to the simplicity of the answer. ;) – Andrew Thompson Apr 25 '12 at 08:40
  • In what way exactly does it 'not work'? It will match because `'[[azerty]'` contains `'[azerty]'`. – ArjunShankar Apr 25 '12 at 08:43
  • @BenjaminGruenbaum Yes Pattern.compile In fact only a matching String is detected but in fact 2 matching strings are in [[azerty] : [azerty AND azerty no ? – Romain G Apr 25 '12 at 08:44
  • To add to that, do you also want it to 'work' with `'[azerty]]'`? Also, why do you want it to work with these seemingly incorrect variable declarations? – ArjunShankar Apr 25 '12 at 08:45
  • Wait, you mean you want greedy mathcing (match the biggest one and not the smallest one)? Change .+? to .+ – Benjamin Gruenbaum Apr 25 '12 at 08:47
  • I want to get all the string that match the pattern. For exemple if I have [[azerty]] , the substring [azerty] is not even detected which is a biggest problem actually – Romain G Apr 25 '12 at 08:50

1 Answers1

1

Perhaps this will help:

(\[[^\[\]]+\])
^ ^^     ^  ^^
| ||     |  ||
| |+-----+  ||
| +---------+|
+------------+

Given a string such as [[azerty], it will skip the first square bracket and match [azerty]. For the string [[azerty][foobar]] it will match [azerty] and [foobar]. Demo here.

Salman A
  • 229,425
  • 77
  • 398
  • 489
  • So for `[[foobar]]` you want it to return both `[foobar]` AND `foobar` to you? – Jack Apr 25 '12 at 09:14
  • yep that's exactly what i want ;) EDIT : for the previous example [[azerty][foobar]] it gives me [azerty] (good) but [[foobar] :/ – Romain G Apr 25 '12 at 09:16
  • @RomainG: about matching matching brackets, AFAIK it is not possible. Read this question: http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets – Salman A Apr 25 '12 at 09:19
  • I've revised my answer to omit the stray `[`. – Salman A Apr 25 '12 at 09:24