Regex for number at the end of string?

℡╲_俬逩灬. 提交于 2019-12-24 00:52:09

问题


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.


回答1:


give this pattern a try,

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



回答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



回答3:


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




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




回答5:


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



来源:https://stackoverflow.com/questions/14294154/regex-for-number-at-the-end-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!