Dan
Dan

Reputation: 109

Java Split RegEx not working

I have been experiencing a lot of difficulties with a very simple task in java. Firstly I would like to split a String to array, every letter alone and use a regex (this is important because i will upgrade it for more complex regex after this but I firstly need this simple one to run)

    Stringbase = "artetbewrewcwewfd";       
    String arr2[] = base.split("\\.");

Why can't I do it like this?

    String base = "artetbewrewcwewfd";       
    String arr2[] = base.split("\\[abcdefghijklmnopqrstuvwxyz]");

nor even like this.

https://ideone.com/cCYVSc

https://ideone.com/DYnh3m

thank you for your time

Upvotes: 1

Views: 1356

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627545

Note that \\. (an escaped dot) in your first regex matches a literal dot character (and your string has no dots, thus, the split returns the whole string).

The second "\\[abcdefghijklmnopqrstuvwxyz]" pattern matches a sequence of [abcdefghijklmnopqrstuvwxyz], because you ruined the character class construct by escaping the first [ (and an escaped [ matches a literal [, thus, the closing ] also is treated as a literal symbol, not a special construct character).

To just split before each character in a string, you can use

String arr2[] = "artetbew42rewcwewfd".split("(?!^)(?=.)");
System.out.println(Arrays.toString(arr2));
// => [a, r, t, e, t, b, e, w, 4, 2, r, e, w, c, w, e, w, f, d]

See the IDEONE demo

Here, (?!^) fails the match at the very start of the string (so as not to return an empty space as first element) and (?=.) is a positive lookahead to match before any character but a newline.

If you want to match before a newline, too, use Pattern.DOTALL flag, or add (?s) before the pattern.

Upvotes: 1

Related Questions