Search code examples
javastringsubstring

Need the words between the " - " ONLY string splitting


Hey I need help splitting a string. The thing is i only need the words between the " - " . for example:

ABC_DEF-HIJ (KL MNOP_QRS)

I need to store DEF in string1 and HIJ in string2

some other formats are

AB (CDE)_FGH IJK/LMN-OPQ (RST

here too string1 = LMN

string2 = OPQ

I only need the words after and before the " - "


Solution

  • So basically you to first split by - and then each side by a non-word character.

    Therefore you can try:

    String s = "ABC_DEF-HIJ (KL MNOP_QRS)";
    String[] splits = s.split("-");  // {"ABC_DEF", "HIJ (KL MNOP_QRS)"}
    
    String[] lefts = split[0].split("[^a-zA-Z]");  // {"ABC", "DEF"}
    String[] rights = split[1].split("[^a-zA-Z]"); // {"HIJ", "", "KL", "MNOP", "QRS"}
    
    String string1 = lefts[lefts.length - 1]; // "DEF""
    String string2 = rights[0];               // "HIJ"