0

I need some regex help, please.

I have the following regex used in PHP:

$module_pattern = "/\[\[mod:(.*?):(.*?):(.*?):(.*?):(.*?)\]\]/i";

It should replace this regex with a module (mod:) and this specific module first :(.*?) and the specific function second :(.*?). I have tried adding the third, fourth and fifth :(.*?) in order to allow for passing parameters to the function, but the above regex assumes that we WILL in fact pass 3 parameters, but I might in some cases pass only one or two.

How do I fix this?

Thanks,

Kobus

2
  • If you're trying to manipulate a set of strings that are delimited with colons, then break apart the string with explode and then manipulate them. Commented Dec 24, 2012 at 22:11
  • 1
    Thank you Andy. Perhaps that would be better. When I started this, I was not sure how complex the string might get, but now that you've mentioned it, explode may just work 100% fine. Commented Dec 26, 2012 at 11:02

1 Answer 1

1

You can create new, optional groups using (...)?. The parameter would be (:(.*?))?. The reason I use a nested group is because you won't want to capture the content, so we can add a ?: to the outer group so it ignores it: (?::(.*?))?.

Your pattern would look like: /\[\[mod:(.*?):(.*?)(?::(.*?))?(?::(.*?))?(?::(.*?))?\]\]/i

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, Patrickdev. I was literally scratching my head trying to figure out how regex works. It is literally a language on its own, it seems :-)
My question is marked as "not a real question" for some reason, but I am having some problems with the regex you wrote for me. I was wondering if you could relook at that for me? It does not work correctly for the second parameter. Could you assist? The output of the regex somehow takes the third and fourth group combined as one, i.e., mod:browse:companies:2:1 is taken as browse, companies, 2:1, 1?
nevermind. Seems like I made a copy-paste error. Seems to work now. :-) I'll keep you posted if anything changes. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.