Andre Pinguin
Andre Pinguin

Reputation: 3

Regex - Capturing an optional string

I want to capture a particular group of strings in a sentence like:

Agent/889 (SIP/1011 from SIP/1011) blablabla (Not in use) blablabla (last was 6 secs ago)

Agent/889 (SIP/1011 from SIP/1011) blablabla (Unavailable) blablabla

I getting all information that I want in this regex:

Agent\/(\d{3})\s\(SIP\/(\d{4}).*\).*(In use|Not in use|Unavailable)\).*

However, I want to get a #4 group, that capture, if exists, the content in "last was # secs ago". I've tried with regex like that:

Agent\/(\d{3})\s\(SIP\/(\d{4}).*\).*(In use|Not in use|Unavailble)\).*(last was \d{1,} secs ago)?

But the #4 group always get a blank value in array, even if the string contains the text in regex. I'm using preg_match_all function of PHP, simulating in this site: PHP Live Regex.

Upvotes: 0

Views: 99

Answers (1)

marvel308
marvel308

Reputation: 10458

You can use the following regex

Agent\/(\d{3})\s\(SIP\/(\d{4}).*\).*(In use|Not in use|Unavailable)\)(?:\w*\s*)*(\(last was \d{1,} secs ago\))?

check the demo here and here

Upvotes: 2

Related Questions