EN
Java - split String by underscore or minus sign - how to make it work?
1 answers
1 points
I have code:
xxxxxxxxxx
1
// split by underscore
2
String[] text1 = "1593521967367_image.jpg".split("_");
3
System.out.println(text1[0]); // 1593521967367
4
5
// minus sign by underscore
6
String[] text2 = "1593521967367-image.jpg".split("-");
7
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:
xxxxxxxxxx
1
// regex with OR: "_|-"
2
String[] text1 = "1593521967367_image.jpg".split("_|-");
Full working example:
xxxxxxxxxx
1
public class Example {
2
3
public static void main(String[] args) {
4
5
// split by underscore
6
String[] text1 = "1593521967367_image.jpg".split("_|-");
7
System.out.println(text1[0]); // 1593521967367
8
9
// minus sign by underscore
10
String[] text2 = "1593521967367-image.jpg".split("_|-");
11
System.out.println(text2[0]); // 1593521967367
12
}
13
}
String.split method takes regex as argument:
xxxxxxxxxx
1
public String[] split(String regex)
0 commentsShow commentsAdd comment