简体   繁体   中英

Regular expression - Extracting strings from a repeating format

EDIT - SOLVED:
Thanks for the responses - I learned that this is actually in serialised format and that there's no need to process it using RegEx.

Apologies for the newb question - and I have tried many many variations, based on StackOverflow answers with no luck. I've also spent a while experimenting with an online Regex tool to try and solve this myself.

This is the string I'm checking :

i:0;s:1:"1";i:1;s:1:"3";i:2;s:1:"5";i:3;s:1:"6";

I'll settle for matching these strings :

i:0;s:1:"1";
i:1;s:1:"3";
i:2;s:1:"5";
i:3;s:1:"6";

But ideally I would like to capture all the values between quotes only.
(there could be anywhere between 1-10 of these kinds of entries)
ie regex_result = [1,3,5,6]

These are some of the regexes I've tried. I've only been able to either capture the first match, or the last match, but not all matches - I'm confused as to why the regex isnt "repeating" as I'd expected:

(i:.;s:1:".";)*

(i:.;s:1:".";)+

(i:.;s:1:".";)+?

Thanks

You can use this regex.

/(?<=:")\d+(?=";)/g

DEMO

"([^"]*)"

Try this .See demo.

http://regex101.com/r/hQ1rP0/43

You need to use \\G so that it would get the number within double quotes which was preceded by i:.;s:1:" ( Here the dot after i: represents any character ). The anchor \\G matches at the position where the previous match ended.

<?php
$string = 'i:0;s:1:"1";i:1;s:1:"3";i:2;s:1:"5";i:3;s:1:"6";';
echo preg_match_all('~(?:i:.;s:1:"|(?<!^)\G)(.)(?=";)~', $string, $match);
print_r($match[1]);
?>

Output:

4Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 6
)

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM