有没有办法在不知道确切索引的情况下找出字符串末尾有多少个数字? [英] Is there a way to find out how many numbers are at the end of a string without knowing the exact index?
问题描述
我有一种从字符串中提取某个子字符串的方法.该子字符串由字符串中的数字组成.然后将其解析为整数.
I have a method that extracts a certain substring from a string. This substring consists of the numbers in the string. Then this is parsed to an integer.
方法:
protected int startIndex() throws Exception {
String str = getWorkBook().getDefinedName("XYZ");
String sStr = str.substring(10,13);
return Integer.parseInt(sStr) - 1;
}
示例:
字符串:
'0 DB'!$B$460
'0 DB'!$B$460
子字符串:
460
好吧,我手动输入了子字符串的索引范围.但我想自动化.
Well, I manually entered the index range for the substring. But I would like to automate it.
我的方法:
String str = getWorkBook().getDefinedName("XYZ");
int length = str.length();
String sStr = str.substring(length - 3, length);
这对于这个例子来说效果很好.
This works well for this example.
现在有一个问题,字符串末尾的数字也可以是4位或5位数字.如果是这样的话,我自然会得到一个NullPointerException
.
Now there is the problem that the numbers at the end of the string can also be 4 or 5 digits. If that is the case, I naturally get a NullPointerException
.
有没有办法或其他方法来找出字符串末尾有多少个数字?
Is there a way or another approach to find out how many numbers are at the end of the string?
推荐答案
在您的情况下,我建议您使用带有 replaceAll 的正则表达式,如下所示:
In your case I would recommend to use regex with replaceAll like this:
String sStr = str.replaceAll(".*?([0-9]+)$", "$1");
这将提取末尾的所有数字或您的字符串或任何长度.
This will extract the all the digits in the end or your String or any length.
此外,我认为您错过了字符串中没有数字的情况,为此我建议您在将其转换为整数之前检查您的字符串.
Also I think you are missing the case when there are no digit in your String, for that I would recommend to check your string before you convert it to an Integer.
String sStr = str.replaceAll(".*?([0-9]+)$", "$1");
if (!sStr.isEmpty()) {
return Integer.parseInt(sStr) - 1;
}
return 0; // or any default value
这篇关于有没有办法在不知道确切索引的情况下找出字符串末尾有多少个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!