Dalius
Dalius

Reputation: 736

PHP Regex: group must end with character but do not capture this character

Example regex:

/^([\w]+:)?other:(.*)$/

Example string:

test:other:words...

The first group would match "test:", but I want it to only capture "test". At first I thought:

/^([\w]+)?:?other:(.*)$/

But I realised I can't have a single : in the beginning. How can I capture a group which if exists must end with : but this : MUST NOT be captured by the group?

Example input and output:

randomString:constantString:somethingElse

should give 'randomString' as first group.

And

constantString:somethingElse

should give the first group as empty

Upvotes: 0

Views: 387

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213223

If you want your first word to be optional, use:

/^(?:(\w+):)?other:(.*)$/

This regex makes \w+: as non-capturing group as a whole, and makes it optional. In addition, it also uses a capture group inside to capture \w+ part.

So, if \w+: is there, the group 1 contains \w+ part, else it contains an empty string.

Upvotes: 2

Enissay
Enissay

Reputation: 4953

Here we go:

^(?:(\w+):)?constantString:(.*)$

(?:) is a non capturing group

Demo

Upvotes: 1

Related Questions