0
var quote = 'some text here [[quote=bob]This is some text bob wrote[/quote]] other text here';

I'm trying to get [[quote=bob]This is some text bob wrote[/quote]].

I was using: match(/[[quote=(.*?)](.*?)[/quote]]/)[1]

but it gives me some text here [[quote=bob]This is some text bob wrote[/quot

Shazboticus S Shazbot
  • 1,289
  • 2
  • 16
  • 27

2 Answers2

3

Try this:

var quote = 'some text here [[quote=bob]This is some text bob wrote[/quote]] other text here';

console.log( quote.match(/(\[\[quote=(.*?)\](.*?)\[\/quote\]\])/) );
// [1] => "[[quote=bob]This is some text bob wrote[/quote]]"
// [2] => "bob"
// [3] => "This is some text bob wrote"
Johan Karlsson
  • 6,419
  • 1
  • 19
  • 28
  • Using `.*` here is not safe as I stated in my answer. Regex will find the longest possible match and so using a different string I get bad results : `'some text here [[quote=bob]This is some text bob wrote[/quote]] other text here[/quote]]'.match(/.*(\[\[quote=.*?\].*?\[\/quote\]\])/); ` gives : `["some text here [[quote=bob]This is some text bob wrote[/quote]]","[[quote=bob]This is some text bob wrote[/quote]]"]` – Johnride Nov 07 '14 at 18:26
  • 1
    @Johnride `.*` does that, not `.*?`. – Johan Karlsson Nov 07 '14 at 18:32
  • 1
    That's one I didn't know about. `?` turns `+` and `*` into non-greedy matches. Nice one. Here take my upvote. – Johnride Nov 07 '14 at 18:38
  • This still fails on nested quotes, e.g. this: "[[quote=foo]some text here [[quote=bob]This is some text bob wrote[/quote]] other text here[/quote]]" (see http://regexr.com/39sa0 for a live example) – Jesse W at Z - Given up on SE Nov 07 '14 at 18:40
  • @JesseWatZ Then it becomes much less straigthforward. Using recursive backrefs or something like that is required. I like regexes, it's a world of ever-ending improving and learning. Mine works a little better with nested quotes but has to be used recursively deleting the previous match. http://regexr.com/39sa3. Mine fails if the quote contains a [ though. – Johnride Nov 07 '14 at 18:43
1

The problem here is that [ is a reserved character in regular expressions so you must escape it to use it as a "regular" character.

Here is a start for you, this will match [quote=bob] from your variable quote.

quote.match(/\[quote=[a-z]*\]/)

Here is the complete, correct and safe version.

string.match(/\[quote=[a-z]*\]([^\[]*)\[\/quote\]/)

Which will return the proper string including the surrounding [quote] tags as first result and only the inner string as second result.

I also used the [a-z] character class as you don't want to match anything after the = character.

Johnride
  • 8,476
  • 5
  • 29
  • 39