从字符串的末尾获取整数(可变长度) [英] Get the Integer from the end of a string (variable length)

查看:139
本文介绍了从字符串的末尾获取整数(可变长度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可变长度的字符串,在字符串的末尾是一些数字。什么是最好/最有效的方法,解析字符串并从最后得到数字作为整数?

I have a string of a variable length and at the end of the string are some digits. What would be the best / efficient way, to parse the string and get the number from the end as an Integer?

字符串和末尾的数字可以是任何长度。例如:

The String and the digits at the end can can be of any length. For example:


abcd123 --> 123
abc12345 --> 12345
ab4cd1 --> 1


推荐答案

以下内容:

final static Pattern lastIntPattern = Pattern.compile("[^0-9]+([0-9]+)$");
String input = "...";
Matcher matcher = lastIntPattern.matcher(input);
if (matcher.find()) {
    String someNumberStr = matcher.group(1);
    int lastNumberInt = Integer.parseInt(someNumberStr);
}

可以做到。

这不是最有效的方式,但除非你有一个围绕这个代码的关键瓶颈(如:从数百万字符串中提取int),这应该足够了。

This isn't necessary the "most efficient" way, but unless you have a critical bottleneck around this code (as: extract int from millions of String), this should be enough.

这篇关于从字符串的末尾获取整数(可变长度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆