Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for number at the end of string?

I want to find out if a string ends with number (with/without decimal). If it ends, I want to extracts it.

"Test1" => 1
"Test"  => NOT FOUND
"Test123" => 123
"Test1.1" => 1.1

I have missed a few details.
1. Prior to number, string can contain special characters also
2. It is single line, not multiline.

like image 995
Tilak Avatar asked Nov 30 '25 11:11

Tilak


2 Answers

give this pattern a try,

\d+(\.\d+)?$

A version with a non-capturing group:

\d+(?:\.\d+)?$
like image 138
John Woo Avatar answered Dec 03 '25 02:12

John Woo


Matches line start, any chars after that and a a number (with optional decimal part) at the end of the string (allowing trailing whitespace characters). The fist part is a lazy match, i.e. it will match the lowest number of chars possible leaving the whole number to the last part of the expression.

^.*?(\d+(?:[.,]\d+)?)\s*$

My test cases

"Test1
"Test
"Test123
"Test1.1
test 1.2 times 1 is 1.2
test 1.2 times 1 is ?
test 1.2 times 1 is 134.2234
1.2
like image 41
Joanna Derks Avatar answered Dec 03 '25 00:12

Joanna Derks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!