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?

6 Answers 6

39

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

7

Integer or float:

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

Comments

0

just match numbers: \d+

Comments

0
// PHP

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

$replacement = '$1.$3';

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

// output 12.2

Comments

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" ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.