Asim Zaidi
Asim Zaidi

Reputation: 28344

Get number between two characters

I am trying to find the number between two underscores (_) in strings like these:

234534_45_92374
3433_9458_034857
zx_8458_047346daf

What would be the regex for this?

Upvotes: -1

Views: 1725

Answers (2)

mickmackusa
mickmackusa

Reputation: 48011

Because your sample strings appear consistently formatted, you do not need to include the validation of matching the trailing underscore.

With preg_match(), match the literal underscore, then forget that you matched it (using \K), then match one or more digits. The match will be a string -- if you need an integer type, then cast the string to an int.

If you definitely want the number to be cast as an integer, PHP offers a more direct function: sscanf(). Silently consume the one or more non-underscore characters, then the underscore, then capture the one or more digit number and use %d to dictate that the value must be an int type variable.

Codes: (Demo)

preg_match('/_\K\d+/', $test, $match);
var_export($match[0]);

Or

sscanf($test, '%*[^_]_%d', $integer);
var_export($integer);

Upvotes: 0

user142162
user142162

Reputation:

preg_match('/_(\d+)_/', $str, $matches);
$number = (int) $matches[1];

Upvotes: 6

Related Questions