I am not able to split the string in java?

Viewed 83

I have some sentences separated by a mixed case token, like :-

String s = "Hi, I am a cool Programmer.GO I love to code in Java language.Go Coding is fun for me.";

Now, I want to split these sentences on "GO" or "Go" (case doesn't matter here).

I am currently doing it like this :-

s.split("GO");

But that only splits on upper case.

1 Answers

String.split takes a regular expression; the "easy" solution is to define two patterns. The first pattern to match capital and lower case "G", and the second to match both cases of "O". We also should remove any white-space before or after the pattern (the \\s* matches none or more white-space). And use \\b to force a boundary,

System.out.println(Arrays.toString(s.split("\\s*\\b[Gg][Oo]\\b\\s*")));

Outputs

[Hi, I am a cool Programmer., I love to code in Java language., Coding is fun for me.]

Another option is the (?i) case-insensitve flag. Like,

System.out.println(Arrays.toString(s.split((?i)\\s*\\bGO\\b\\s*)));

For the same result.

Related