Get numbers from string with regex
Asked Answered
F

6

22

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?

Four answered 25/6, 2009 at 12:24 Comment(0)
P
38

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.

Piwowar answered 25/6, 2009 at 12:28 Comment(0)
F
7

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.

Fayre answered 25/6, 2009 at 12:29 Comment(0)
P
7

Integer or float:

/\d+((.|,)\d+)?/
Pneuma answered 11/1, 2014 at 16:12 Comment(0)
E
0

just match numbers: \d+

Embryotomy answered 25/6, 2009 at 12:29 Comment(0)
H
0
// PHP

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

$replacement = '$1.$3';

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

// output 12.2
Haversine answered 4/9, 2018 at 10:37 Comment(0)
T
0

For JS:

const myNewString = 'I am here 1 day per 2 weeks in 3 years'
myNewString.match(/[1-9]+/g)

// Array(3) [ "1", "2", "3" ]
Tergiversate answered 25/5 at 3:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.