Jump to content

Regular expression puzzle


jhsachs

Recommended Posts

I've been banging my head on a regular expression problem for an hour or more. Whatever's wrong, I'm not seeing it.

 

I've got a multi-line string that contains placeholders in the form '$xxx[yyy]'. The regular expression is supposed to parse the string into the text before the placeholder, the xxx, the yyy, and the text after the placeholder.

 

The pattern is

 

$pattern = '/^(.*?)\$(.*?)\[(.*?)\](.*)/';

 

It works, except that the fourth part of the match contains the text after the placeholder only up to the end of the current line.

 

I think (.*) should match to the end of the string. Why doesn't it?

 

I tried adding a dollar sign to the end of the pattern. I didn't see why it should be necessary, but I thought it might help. Instead it made the match fail.

 

Why isn't this working?

 

I'm currently running the code under Windows. The line end is represented by <cr><lf>. Since I'm not searching for line ends, though, I don't think the form should matter.

Link to comment
https://forums.phpfreaks.com/topic/243404-regular-expression-puzzle/
Share on other sites

most likely because there are spaces and newlines that will break your expression... the " . " character will not match spaces or newlines by default, so a modifier is needed to allow it to match these cases..

 

$pattern = '/^(.*?)\$(.*?)\[(.*?)\](.*)/s'; //adding the s modifier will allow .* to capture spaces and new lines as well

Goldurn, you learn something every day. If you're lucky, at least.

 

My standard reference for regexes says the the dot matches any character except \r and \n, including spaces, and my own experience is consistent with that. The \r\n exception is important, though, and I probably wouldn't have found it on my own without a lot more pain. Thanks for pointing that out.

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.