我远未掌握正则表达式,但我想在第一次和最后一次下划线上分割字符串,例如在第一次和最后一次下划线上用正则表达式分割字符串。
"hello_5_9_2018_world"
to
"hello"
"5_9_2018"
"world"我可以在最后一个下划线上用
String[] splitArray = subjectString.split("_(?=[^_]*$)");但我无法弄清楚如何在第一个下划线上分开。
有人能告诉我怎么做吗?
谢谢大卫
发布于 2018-05-09 16:33:59
虽然其他答案实际上更好更好,但如果您真的想使用split,这是一个好方法:
"hello_5_9_2018_world".split("((?<=^[^_]*)_)|(_(?=[^_]*$))")
==> String[3] { "hello", "5_9_2018", "world" }这是您的前瞻性模式(_(?=[^_]*$))的组合。
和对称的后视模式:((?<=^[^_]*)_)
(匹配由_ (字符串的开始)和[^_]* (0.n非下划线字符)执行的[^_]*)。
发布于 2018-05-09 16:15:30
你不需要正则表达式就可以实现这一点。您可以通过查找_的第一个和最后一个索引并根据它们获取子字符串来实现这一点。
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));上述指纹
hello
5_9_2018
world注意:
如果字符串没有两个_,您将得到一个StringIndexOutOfBoundsException。
为了防止这种情况,您可以检查提取的索引是否有效。
firstIndex == lastIndex == -1,则表示该字符串没有任何下划线。firstIndex == lastIndex,则该字符串只有一个下划线。发布于 2018-05-09 16:17:06
正则表达式
(?<first>[^_]+)_(?<middle>.+)+_(?<last>[^_]+)Java代码
final String str = "hello_5_9_2018_world";
Pattern pattern = Pattern.compile("(?<first>[^_]+)_(?<middle>.+)+_(?<last>[^_]+)");
Matcher matcher = pattern.matcher(str);
if(matcher.matches()) {
String first = matcher.group("first");
String middle = matcher.group("middle");
String last = matcher.group("last");
}https://stackoverflow.com/questions/50257781
复制相似问题