1

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

9
  • So you try to split a String without any dot on a dot ... and what do you expext there? I mean you explicitly escaped your regex, so I guess you know what you're doing? Commented May 26, 2016 at 20:29
  • Try String arr2[] = "artetbew42rewcwewfd".split("(?!^)(?=.)"); Commented May 26, 2016 at 20:33
  • dot is a symbol for any character in regex as far as I know? Commented May 26, 2016 at 20:34
  • 1
    An unescaped dot (or not inside a character class) with DOTALL mode matches any character. Commented May 26, 2016 at 20:38
  • Yes, dot ., you're looking for the character dot, which is \\. and something different. Commented May 26, 2016 at 20:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.