EN
Java - split String by underscore or minus sign - how to make it work?
1
answers
1
points
I have code:
// split by underscore
String[] text1 = "1593521967367_image.jpg".split("_");
System.out.println(text1[0]); // 1593521967367
// minus sign by underscore
String[] text2 = "1593521967367-image.jpg".split("-");
System.out.println(text2[0]); // 1593521967367
It works ok, but is it possible to have 1 split by "_" or "-" character, instead of 2 separated splits?
1 answer
2
points
We can use regex in String split method.
Regex which solves the problem:
// regex with OR: "_|-"
String[] text1 = "1593521967367_image.jpg".split("_|-");
Full working example:
public class Example {
public static void main(String[] args) {
// split by underscore
String[] text1 = "1593521967367_image.jpg".split("_|-");
System.out.println(text1[0]); // 1593521967367
// minus sign by underscore
String[] text2 = "1593521967367-image.jpg".split("_|-");
System.out.println(text2[0]); // 1593521967367
}
}
String.split method takes regex as argument:
public String[] split(String regex)
0 comments
Add comment