0

I'm trying to split my regex but it's not splitting for some reason. Here's my code

String str = "sdef@srdfsrd[es[edf@edfv";
String[] arrOfStr = str.split("\\@\\["); 
for (String a : arrOfStr) 
{
  System.out.println(a);
}

output:

sdef@srdfsrd[es[edf@edfv

expected output:

sdef
srdfsrd
es
edf
edfv

The same problem for:

String[] arrOfStr = str.split(",:");  //not splitting the word at all

2 Answers2

4

"\\@\\[" matches @[, which is not in your string. Change your RegEx to "[@\\[]", which is a character class - that means it will split on either @ or [.

See a demo here :)

bkis
  • 2,530
  • 1
  • 17
  • 31
1

Use "@|\\[ instead of \\@\\[

Note that in regex pattern, | works as OR i.e. by using "@|\\[ you are instructing the code to split the given string either on @ OR on [

Alternatively, you can use [@\\[] where [] specifies the character classes.

Demo:

public class Main {
    public static void main(String[] args) {
        String str = "sdef@srdfsrd[es[edf@edfv";
        String[] arrOfStr = str.split("@|\\[");
        for (String a : arrOfStr) {
            System.out.println(a);
        }
    }
}

Output:

sdef
srdfsrd
es
edf
edfv
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110