Mithun Sreedharan
Mithun Sreedharan

Reputation: 51282

How to extract key value pairs from a specific format string using regular expression?

I have a string with a specific format

'a:3:{s:8:"postid";s:1:"100";s:6:"commentid";s:1:"200";s:6:"website";s:24:"http://www.example.com";}';

Please note that above string is not JSON, serialized object or any other data format.

May requirement is to extract the each value in the double quotes and map with the next item in the double quotes.

My required output is an array map

[postid:100, commentid:200, website:"http://www.example.com"]

Is this possible to achieve with regular expression? provided keys postid, commentid and website will be always present in the input string.

Upvotes: 0

Views: 696

Answers (2)

sp00m
sp00m

Reputation: 48837

This simple one should suit your needs:

"([^"]+)"[^"]+"([^"]+)"

Regular expression visualization

Debuggex Demo

As you can see, the first group will contain the key and the second one the value.

Demo on regex101

Upvotes: 2

vks
vks

Reputation: 67978

"(.*?)";[a-zA-Z]*:\d*:\"(\S+?)"

Try this.This will give all groups.See demo.

http://regex101.com/r/cT1rH4/1

Upvotes: 1

Related Questions