Wednesday, 7 June 2017

javascript - regex find all the strings preceded by = and ending in &

If your regex engine supports lookbehinds/lookaheads:


(?<==).*?(?=&)

Otherwise use this:


=(.*?)&

and catch capture group 1.


If your regex engine does not support non-greedy matching replace the .*? with [^&]*.




But as zzzzBov mentioned in a comment, if you're parsing GET URL prefixes there are usually better native methods for parsing GET arguments.


In PHP for example there would be:


$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
?>

(As found on php.net.)


Edit: Appears you're using Javascript.


Javascript solution for parsing query string into object:


var queryString = {};
anchor.href.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);

Source: http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...