I have JS file and I need to parse that array in it:
something: ['Prefix.All','Ignore.Me','Prefix.Another']
I need to get all elements from "something" array with defined prefix. Now I can get it, if array will contain only one element. My regexp:
String: something: ['Prefix.All']
Can get element with:
/something\s*:\s*\[['"](Prefix[a-zA-Z0-9.]+)['"]]/
But how to find many elements in array? And how to find more than one "something" array in file?
2 Answers 2
In PHP you need to do it in two steps (which is probably better anyway - cramming everything into a single regex isn't always the best idea).
First, match the array you're looking for. Note that this regex requires that there are no brackets between the delimiters [ and ], so nested arrays or strings that contain brackets will cause the regex to fail (as in "match the wrong text"):
if (preg_match('/\bsomething: \[([^[\]]*)\]/', $subject, $regs)) {
$result = $regs[1];
}
This will find the first occurrence of a string like something: ['Prefix.All','Ignore.Me','Prefix.Another'] and put 'Prefix.All','Ignore.Me','Prefix.Another' into $result.
Then you can get all the matches from that:
preg_match_all('/\bPrefix[^\']*/', $result, $final, PREG_PATTERN_ORDER);
$final = $final[0];
Comments
In regex you can group a token with (), and ask for it many times with *.
So: (something)*would give you every instance of the word 'something'.
Further: (__your__token__here__)* finds every instance of your token.
Paste some of your array here: http://gskinner.com/RegExr/ and use the regex builder to test your regex
Does that help?
4 Comments
(create[\d])(something)* matches "", "something", "somethingsomething" etc., but it doesn't do at all what the OP wants.* wouldn't work.
Prefix.AllI would suggest you to split it bycomma...[, find last]. take substring in[ ], split it by,. find all substrings, that have prefixPrefix. Why you think, that regexp can really helps you?