How to Match Multiple Occurrences with a Regex in JavaScript Similar to PHP's Preg_Match_All()

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

Hoisted from the comments

2020 comment: rather than using regex, we now have URLSearchParams, which does all of this for us, so no custom code, let alone regex, are necessary anymore.

– Mike 'Pomax' Kamermans

Browser support is listed here https://caniuse.com/#feat=urlsearchparams


I would suggest an alternative regex, using sub-groups to capture name and value of the parameters individually and re.exec():

function getUrlParams(url) {
var re = /(?:\?|&(?:amp;)?)([^=&#]+)(?:=?([^&#]*))/g,
match, params = {},
decode = function (s) {return decodeURIComponent(s.replace(/\+/g, " "));};

if (typeof url == "undefined") url = document.location.href;

while (match = re.exec(url)) {
params[decode(match[1])] = decode(match[2]);
}
return params;
}

var result = getUrlParams("http://maps.google.de/maps?f=q&source=s_q&hl=de&geocode=&q=Frankfurt+am+Main&sll=50.106047,8.679886&sspn=0.370369,0.833588&ie=UTF8&ll=50.116616,8.680573&spn=0.35972,0.833588&z=11&iwloc=addr");

result is an object:


{
f: "q"
geocode: ""
hl: "de"
ie: "UTF8"
iwloc: "addr"
ll: "50.116616,8.680573"
q: "Frankfurt am Main"
sll: "50.106047,8.679886"
source: "s_q"
spn: "0.35972,0.833588"
sspn: "0.370369,0.833588"
z: "11"
}

The regex breaks down as follows:


(?: # non-capturing group
\?|& # "?" or "&"
(?:amp;)? # (allow "&", for wrongly HTML-encoded URLs)
) # end non-capturing group
( # group 1
[^=&#]+ # any character except "=", "&" or "#"; at least once
) # end group 1 - this will be the parameter's name
(?: # non-capturing group
=? # an "=", optional
( # group 2
[^&#]* # any character except "&" or "#"; any number of times
) # end group 2 - this will be the parameter's value
) # end non-capturing group

Regex javascript result different than expected

Regexp.prototype.exec() just returns the first occurrence of a match, you have to call it in a loop to get all the matches.

Simpler is to use String.prototype.match(), it returns an array of all the matches.

You only need to use exec() if you also need to get the capture groups.

var reg = new RegExp('[">]\\$[^"<> ]*["<]', 'g');var str = '<span>$name</span><img src="$images[0].src"><img src="$images[1].src"><img src="$images[2].src">';var match = str.match(reg);console.log(match);

Regex php preg_match multiple occurrences in string

Thsi regex should work for you:

<?php 
$ptn = "#(?:By([A-Za-z]+?))(?=By|$)#";
$str = "findByByteByHouseNumber";
preg_match_all($ptn, $str, $matches, PREG_PATTERN_ORDER);
print_r($matches);
?>

this will be the output:

Array
(
[0] => Array
(
[0] => ByByte
[1] => ByHouseNumber
)

[1] => Array
(
[0] => Byte
[1] => HouseNumber
)

)

Preg_match_all split multiple occurrences

Try this:

$string="59|https://site59.com20|https://site20.com30|https://site30.com16|https://site15.com66|https://site66.com29|https://site29.com";
preg_match_all("/(?:[0-9][0-9](?:\|)(?:https\:\/\/)(.*?)(?=[\d][\d]\||$))|([\d][\d]\|.*)/", $string, $matches);

Results array in $matches:

[0] => 59|https://site59.com
[1] => 20|https://site20.com
[2] => 30|https://site30.com
[3] => 16|https://site15.com
[4] => 66|https://site66.com
[5] => 29|https://site29.com

How do we fetch multiple occurrences of a regex in a single string in Groovy?

Try this:

def str = '{"jobs":[{"id":"6369c112a2ee5ca08adaa1d01b7e5c74","status":"RUNNING"},{"id":"bbfd87f15334c8e27b40bc46896e95c7","status":"RUNNING"},{"id":"90c5a32e8300da7d43ce351f7f72f0d2","status":"RUNNING"}]}'
def pattern = /(?<="id":")\w+(?=")/
def matcher = str =~ /$pattern/
assert matcher.collect() == ["6369c112a2ee5ca08adaa1d01b7e5c74", "bbfd87f15334c8e27b40bc46896e95c7", "90c5a32e8300da7d43ce351f7f72f0d2"]

Regex to match strings starting and ending with %%

Use preg_match_all because you need multiple matches.

PHP preg_match_all with Multiple Words

You can use several lookaheads:

$text = 'After A!!BC DEF hello bugggy bad Sled bob bobert robob Triumph 2000 Roadster clearing bobby Sledmere ^ August 2014 ^ error';   
$pattern = '~^(?=.*\bbob)(?=.*\bbug)(?=.*\bsled)~i';
if (preg_match($pattern, $text)) echo 'OK!';

Why does preg_match match multiple empty strings

You attempted to capture 4 different things with the () syntax. Therefore, there will be 4 different elements in the $matches array. Only the last capture will match the string 123 (^[123]+$).

See the documentation



Related Topics



Leave a reply



Submit