James Andrew
James Andrew

Reputation: 7243

Simple JavaScript regex to parse tags

I have a simple regex:

\[quote\](.*?)\[\/quote\]

Which will replace [quote] by table, tr and td. (and [/quote] by /td, /tr and /table)

It works perfectly for multiple separate quotes in the same string:

IE:

[quote]
Person 1
[/quote]
Person 3 talking about a quote

[quote]
Person 2
[/quote]
Person 3 talking about another quote.

But when it tries to replace multiple (non-separate) quote in the same string:

IE:

[quote]
[quote]
Person 1
[/quote]
Person 2 quoting person 1
[/quote]
Person 3 quoting person 2 and 1

It messes up, (matches the first quote to the first /quote when it should be matching second quote to first /quote and first quote to last /quote)

How would I edit the regex so it works in both examples?

Upvotes: -1

Views: 135

Answers (3)

patorjk
patorjk

Reputation: 2182

I created an example JavaScript BBCode parser that handles that situation. I think I got around that situation because JavaScript's string replace function can take in another function, so you can make your parser recursively work with smaller sections of the input. However, it's been a while since I've looked at it. You can see it in action here and download it on the same page (the download link is under the header - "You can download the JavaScript module for this here."):

http://patorjk.com/bbcode-previewer/

Upvotes: 0

Imran
Imran

Reputation: 91029

Regex isn't a good choice for parsing nested structured text. See this question for JavaScript BBCode parser

Upvotes: 2

iwg
iwg

Reputation: 528

Try this one:

\[quote\]{1,}(.*?)\[\/quote\]

Upvotes: 0

Related Questions