Regex for number at the end of string?
Solution 1
give this pattern a try,
\d+(\.\d+)?$
A version with a non-capturing group:
\d+(?:\.\d+)?$
Solution 2
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
Solution 3
Use the following regex in c# (\d+)$
Solution 4
A regex for a string that ends with a number: @"\d$"
. Use http://regexpal.com/ to try out regexes.
Of course, that just tells you that the last character is a number. It doesn't capture anything other than the last character. To capture the number only this is needed: @"\d*\.?\d+$"
.
If your string can be more complicated, eg "Test1.2 Test2", and you want both numbers: @"\d*\.?\d+\b"
.
Solution 5
use this regex [a-zA-Z]+\d+([,.]\d+)?\b$
if you want digit only use this one (?<=[a-zA-Z]+)\d+([,.]\d+)?\b$
Tilak
profile for Tilak on Stack Exchange, a network of free, community-driven Q&A sites http://stackexchange.com/users/flair/327255.png .NET Software programmer with interest in WPF, Linq, Debugging, Multithreading, and Design Patterns. Profile
Updated on July 13, 2022Comments
-
Tilak almost 2 years
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. -
Johanna Larsson over 11 years@JoannaTurban the regex works for the last example too. It just checks whether the last character in the string is a number.
-
Johanna Larsson over 11 years@Esailija ah I misunderstood, I thought he wanted to know if the string ended with a number. In that case he could just grab the whole string, was my reasoning!
-
Joanna Derks over 11 yearsif you make the dot and the digits after the dot separate optional groups you can end up with a match "1."
-
Johanna Larsson over 11 years@JoannaTurban fair point, I wonder if .2 should be a valid number