4

I have a string like

abababa:nsndnfnng.leleelld_kdjdh

I want to split it on ":" and ".", so that I get a list as follows:

{abababa, nsndnfnng, eleelld_kdjdh}

how can I do this with calling the split() once?

Alex
  • 573
  • 1
  • 10
  • 23

3 Answers3

8

You are looking for String#split method. Since it accepts regex which will describe delimiter your code could look like

String[] result = yourString.split("[:.]");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

You can just use String.split("[:.]") which takes a regex argument

Common pitfall If you would only want to split on . alone you have to escape the dot String.split("\\.") (or use a character class here too String.split("[.]"))

gustf
  • 1,959
  • 13
  • 20
  • 2
    `:` and `.` are not special in character class. There is no need to escape them there. – Pshemo Apr 05 '16 at 18:49
  • "Note that the dot . *needs* to be escaped." that would be true if `.` would not be inside `[...]`. Most regex metacharacters have no special meaning in character class because its purpose is to represent single characters, which means we can even write `[+/:*()]` and it will represent single `+` `/` `:` `*` `(` or `)` characters. Same about `[.]`. You can find more info here: http://www.regular-expressions.info/charclass.html#special – Pshemo Apr 05 '16 at 18:57
  • You are right since they are within a *Character class*, did not think about that – gustf Apr 05 '16 at 18:58
  • 1
    If you agree that "Note that the dot . needs to be escaped" is not right (as `.` is placed in `[..]`) feel free to remove that part from your answer as it is incorrect. – Pshemo Apr 05 '16 at 19:00
0

use regex and split the string

Example:

public static void main(String[] args) {
    String REGEX_PATTERN = "[:.\\_]";
    String s1 = "abababa:nsndnfnng.leleelld_kdjdh";
    String[] result = s1.split(REGEX_PATTERN);
    for (String myString : result) {
        System.out.println(myString);
    }
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97