Jump to content

RegEx lookaheads


Fmdpa

Recommended Posts

Here's my regex:

(\[b\])(?=[\w\d].*?\[\/b\])

I want to match the [ b ] tag, as long as there is a closing tag. eg:

[b]bold text[/b] //match [b] and [/b]

The regex I posted above matches the first tag if there is a closing tag, but when I try to also match the closing [ /b ] tag, it fails.

(\[b\])(?=[\w\d].*?\[\/b\])(\[\/b\])

How can I solve this?

Link to comment
Share on other sites

Your look-ahead expression only tests to see if all that stuff follows the first [b]. It doesn't actually try to match all that stuff. So after it finds the first [b], the attempt to match resumes immediately after the [b]. So you need to account for all the characters between [b] and [/b]. I know that seems redundant, and I would like to believe a regex genius knows a better way, but that's all I got.Since the look-ahead already specifies what you're looking for between the tags, I think a simple .* can do the job. I tested it a little, and it seemed okay.

$re='/(\[b\])(?=[\w\d].*?\[\/b\]).*(\[\/b\])/';								 ^^here

But you'll really want to hammer on this thing.I'm not sure why you want it set up this way, though. Doesn't it defeat the point of the look-ahead?

Link to comment
Share on other sites

I guess it does seem redundant now that you mention it. But thanks for your help (your first post solved my problem). I guess I was just too excited about lookahead/lookbehinds, having just learned how to use them recently.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...