2

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.

Tilak
  • 30,108
  • 19
  • 83
  • 131

5 Answers5

10

give this pattern a try,

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

A version with a non-capturing group:

\d+(?:\.\d+)?$
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
John Woo
  • 258,903
  • 69
  • 498
  • 492
3

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
Joanna Derks
  • 4,033
  • 3
  • 26
  • 32
3

Use the following regex in c# (\d+)$

sreejithsdev
  • 1,202
  • 12
  • 26
2

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

Johanna Larsson
  • 10,531
  • 6
  • 39
  • 50
1

use this regex [a-zA-Z]+\d+([,.]\d+)?\b$ if you want digit only use this one (?<=[a-zA-Z]+)\d+([,.]\d+)?\b$

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52