Top community members

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

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

1 points
Asked by:
Root-ssh
5171

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
5171

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more