Raphael Jeger
Raphael Jeger

Reputation: 5232

Get numeric value between unique string and underscore

Can someone tell me how to get "123" out of this string with regex:

.../groups/123_abc/...

I am sure that

/groups/

is unique in that string.

Upvotes: 0

Views: 161

Answers (3)

mickmackusa
mickmackusa

Reputation: 48011

Unnecessarily using lookarounds in a regex pattern can lead to poor performance.

This task does not require any lookarounds. Match the leading, literal /groups/ subsrtring, then release it from the full string match using \K, then match the desired digits.

Code: (Demo)

$str = '.../groups/123_abc/...';

var_export(
    preg_match('#/groups/\K\d+#', $str, $m)
    ? $m[0]
    : null
);

If you use explode() as an alternative to the above script, you will need to remove the unwanted characters from element [1] using a second technique.

Upvotes: 0

vks
vks

Reputation: 67988

(?<=groups\/)\d+

Try this.See demo.

https://regex101.com/r/sJ9gM7/57

$re = "/(?<=groups\\/)\\d+/im";
$str = ".../groups/123_abc/...";

preg_match_all($re, $str, $matches);

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59282

Whatever may be the language, you can split on "/groups/" and then take the second element, which is at index 1.

Then split on _ and take the first element which is at index 0.

Upvotes: 2

Related Questions