我远不是掌握正则表达式,但我想在第一个和最后一个下划线上拆分字符串,例如将字符串拆分为第一个和最后一个下划线和正则表达式
"hello_5_9_2018_world"
to
"hello"
"5_9_2018"
"world"
Run Code Online (Sandbox Code Playgroud)
我可以将它拆分为最后一个下划线
String[] splitArray = subjectString.split("_(?=[^_]*$)");
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何拆分第一个下划线.
谁能告诉我怎么做到这一点?
谢谢大卫
没有正则表达式就可以实现这一点.您可以通过查找_基于它们的第一个和最后一个索引并获取子字符串来实现此目的.
String s = "hello_5_9_2018_world";
int firstIndex = s.indexOf("_");
int lastIndex = s.lastIndexOf("_");
System.out.println(s.substring(0, firstIndex));
System.out.println(s.substring(firstIndex + 1, lastIndex));
System.out.println(s.substring(lastIndex + 1));
Run Code Online (Sandbox Code Playgroud)
以上打印
hello
5_9_2018
world
Run Code Online (Sandbox Code Playgroud)
注意:
如果字符串没有两个,_你会得到一个StringIndexOutOfBoundsException.
为了防止它,您可以检查提取的索引是否有效.
如果firstIndex== lastIndex== -1则表示该字符串没有任何下划线.
如果firstIndex== lastIndex则字符串只有一个下划线.