我有一个如下所示的字符串。我需要从下面的字符串中提取数字 123
并且它可以位于如下所示的任何位置,但字符串中只有一个数字并且它始终采用相同的格式 _number_
text_data_123
text_data_123_abc_count
text_data_123_abc_pqr_count
text_tery_qwer_data_123
text_tery_qwer_data_123_count
text_tery_qwer_data_123_abc_pqr_count
代码如下:
String value = "text_data_123_abc_count";
// this below code will not work as index 2 is not a number in some of the above example
int textId = Integer.parseInt(value.split("_")[2]);
执行此操作的最佳方法是什么?
最佳答案
有点guava魔法:
String value = "text_data_123_abc_count";
Integer id = Ints.tryParse(CharMatcher.inRange('0', '9').retainFrom(value)
关于java - 如何从特定格式的字符串中提取数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31972560/