0

I'm trying to split the characters of the String to a String array. I found the solution here.

The solution is perfect, however I don't get how .split("(?!^)") worked. I'm familiar with the basics of split() method. Can someone provide an explanation?

Community
  • 1
  • 1
kir
  • 581
  • 1
  • 6
  • 22
  • Take a look at the Javadoc from the Pattern Class http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html – Julien Sep 08 '13 at 21:25
  • 1
    Welcome to regular expression world – fujy Sep 08 '13 at 21:25
  • The split method takes the ´String´ representation of a regular expression as argument. More information [here](http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html). Take a look at lookaheads especially in your case. – Mena Sep 08 '13 at 21:26

1 Answers1

7

(?!^) is a regular expression consisting of a negative lookahead. ^ is an anchor used to signify the start of the string. (?!^) matches all 0-length strings that are not followed by ^, the start of the string. In other words, it matches all 0-length strings except that at the start of the string.

For example, in the string abc, there will be 3 matches: one between a and b, one between b and c, and one after the c. Splitting on these matches produces the desired array (note that the 1-argument version of split() discards any trailing empty strings, which is why none are included in the resulting array).

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • Thanks for the explanation, especially the reference links. My book never covered this stuff, so I guess I can't use it in class. – kir Sep 08 '13 at 21:41
  • @user2280704 No problem, glad I could help. I personally would never use this approach since it's simply unclear and unnecessary. I would prefer a regular loop to create the array. – arshajii Sep 08 '13 at 22:00