简体   繁体   English

使用正则表达式从字符串中获取数字

[英]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.那么$1 (Perl) 或$matches[1] (PHP) 或任何您选择的毒药,都应该包含数字。

整数或浮点数:

/\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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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