0

I would like to match the following string:

[-ed, -ing, -ment <i>n.</i>]

But exclude:

[-ed, -ing, -ment <b>n.</b>]

And my regex is:

   \[[\-,\s\.(<i>)(</i>)a-z]+\]

Which won't work.

I add brackets to <i> so it appears as a whole, so <b> wont be matched.

However, brackets inside square brackets don't seem to work.

James King
  • 1,284
  • 3
  • 13
  • 23
  • How do you think that regex works? Escaping the square brackets means they'll match literal square brackets, so how is `\-,()()a-z` supposed to match `-ed, -ing, -ment n.`?! – Biffen Feb 11 '15 at 11:14
  • I noticed that problem you mentioned and rectified it. But `\[[\-,()()a-z]+\]` wont work either. – James King Feb 11 '15 at 11:17
  • (After an edit.) Now you're just misunderstanding character classes (`[...]`). `[\-,()()a-z]` is equivalent to `[<>,\/()aiz-]`. May I suggest you read a regex tutorial? – Biffen Feb 11 '15 at 11:18
  • Are you sure? `a-z` means any alphabet from a to z, that is `a, b, c, d...z` – James King Feb 11 '15 at 11:23
  • Ooops, my bad. It should be `[<>,\/()a-z-]`. It matches `` because `` are all in there. ‘*I add brackets to `` so it appears as a whole*‘, that's where you're wrong; you've simply added ``, `/`, `(`, `)` and `i` to the class, most of them twice. – Biffen Feb 11 '15 at 11:24
  • Yes, your right. my question is how to match someting as a whole inside a square bracet, if `()` is not the solution. – James King Feb 11 '15 at 11:34

1 Answers1

2

The following works with the sample string:

\[([^<>]|<i>.*?<\/i>)+?\]

I.e. square brackets containing a number of things that are either a single character that is neither < nor >, or <i>[...]</i> with some content.

It will match the first string and not the second. The problem description however is quite vague, so the regex might need some tweaking. E.g:

  • Is it just <i> or anything but <b>?

  • Can the square brackets contain nested square brackets?

  • Are the contents of the square brackets in fact comma-separated elements that must all begin with a hyphen?

Biffen
  • 5,354
  • 5
  • 27
  • 32