Java 如何按最后一个下划线分割字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24015314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to split a string by last underscore
提问by agarwal_achhnera
I have to split a string with underscore. String may have many number of underscore but I have to split this with last underscore. How can I do this with simple split method using regex?
我必须用下划线分割一个字符串。字符串可能有很多下划线,但我必须将其与最后一个下划线分开。如何使用正则表达式通过简单的拆分方法来做到这一点?
采纳答案by lpratlong
You can use lastIndexOf
on String
which returns you the index of the last occurrence of a chain of caracters.
您可以使用lastIndexOf
on String
which 返回最后一次出现的字符链的索引。
String thing = "132131_12313_1321_312";
int index = thing.lastIndexOf("_");
String yourCuttedString = thing.substring(0, index);
It returns -1
if the occurrence is not found in the String.
-1
如果在字符串中未找到出现,则返回。
回答by Mark Taylor
You can use the String last index of method, this returns an int, which you can then pass into the subString method.
您可以使用 String 方法的最后一个索引,这将返回一个 int,然后您可以将其传递给 subString 方法。
String code = "123_456_789";
String subString = code.subString(code.lastIndexOf("_"));
回答by Ankit Lamba
You can use String#lastIndexOf(String str)
, try :
您可以使用String#lastIndexOf(String str)
,尝试:
int lastIndexOf = str.lastIndexOf("_");
String substring1 = str.substring(0, lastIndexOf);
String substring2 = str.substring(lastIndexOf+1, str.length());
回答by Evgeniy Dorofeev
try this
尝试这个
String[] a = s.split("_(?!.*_)");