Languages

Java - split String by underscore or minus sign - how to make it work?

1 points
Asked by:
Root-ssh
7626

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 answers
2 points
Answered by:
Root-ssh
7626

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join