简体   繁体   中英

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.

尝试这种模式,

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

Matches line start, any chars after that and aa number (with optional decimal part) at the end of the string (allowing trailing whitespace characters). The fist part is a lazy match, ie 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

在c# (\\d+)$使用以下正则表达式

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

使用这个正则表达式[a-zA-Z]+\\d+([,.]\\d+)?\\b$如果你想要数字只使用这个(?<=[a-zA-Z]+)\\d+([,.]\\d+)?\\b$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM