user532104
user532104

Reputation: 1423

How to get the integer part from a string using regex

string $str  = "hello768gonf123";

How do I get the numbers at the end (i.e. 123) using regex?

Upvotes: 1

Views: 119

Answers (2)

codaddict
codaddict

Reputation: 454950

If the integer is always found at the end of the string(hello768gonf123), you can use:

(\d+)$

If you want to capture the integer closer to the end (123 from hello768gonf123foo) you can use:

(\d+)\D*$

Upvotes: 5

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

The regexp ".*([0-9]+)" matches anything followed by a series of one or more digits, and returns the digits as the (only) capture group.

Upvotes: 1

Related Questions