简体   繁体   中英

Get numbers from string with regex

I am trying to write a regex to get the numbers from strings like these ones:

javascript:ShowPage('6009',null,null,null,null,null,null,null)
javascript:BlockLink('2146',null,null,null)

I am having difficulty writing the regex to grab these numbers.

How should I do this?

Try this:

(\d+)

What language are you using to parse these strings?

If you let me know I can help you with the code you would need to use this regular expression.

Assuming:

  • you want to capture the digits
  • there's only one set of digits per line

Try this:

/(\d+)/

then $1 (Perl) or $matches[1] (PHP) or whatever your poison of choice is, should contain the digits.

整数或浮点数:

/\d+((.|,)\d+)?/

只匹配数字:\\d+

// PHP

$string = 'ssss 12.2';
$pattern = '/\D*(\d+)(.|,)?(\d+)?\D*/';

$replacement = '$1.$3';

$res = (float)preg_replace($pattern, $replacement, $string);

// output 12.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM