1

I hope there are some regexp experts that can help. I have been searching for hours but can not find an answer.

This is the input string:

parameters:x,y,123,z;parameters:a,b,456,c;

The puzzle is to retreive the last parameters part (a,b,456,c) and I know it starts with "parameters:" and ends with ",c";

So I tried the following regexp:

parameters:(.+?,c);

This matches not the expected last part but the starting from the first parameters. This is the match group:

x,y,123,z;parameters:a,b,456,c

So the ? for doing a lazy match is not lazy enough as it matches more then I want.

Any suggestions?

1
  • Why not splitting by semicolon ;, then match? Commented Mar 1, 2013 at 16:57

2 Answers 2

4

The regex is exactly doing what you have defined: It matches "parameters" and then lazy till the first "c" it finds.

Try this:

parameters:([^;]+,c);

[^;] is a negated character class, that matches every character but ";". It seems that ; can not occur within such a group.

See it here on Regexr

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

Comments

3

The simplest way would be to forbid : and ; from matching:

parameters:([^:;]+,c);

Or you can be more explicit and forbid parameters from matching twice:

parameters:((?:(?!parameters).)+,c);

The reason why your regex wasn't lazy enough is that the regex match starts at the earliest possible position, and .+? matches as much as necessary (which, from the first parameters: in the string, is exactly the string you found it to match).

1 Comment

Never thought of using a forbid construction. Works perfectly.

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.