Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does splitting on `(?!^)` and `(?<!^)` produce the same answer?

Tags:

java

regex

The following two lines of code:

System.out.println(Arrays.toString("test".split("(?<!^)")));
System.out.println(Arrays.toString("test".split("(?!^)")));

each produce the same output:

[t, e, s, t]

I expected the bottom line to produce

[, t, e, s, t]

since it should be willing to split after the ^ and before the t. Can someone point out where my thinking is wrong?

like image 889
Keppil Avatar asked Oct 21 '13 20:10

Keppil


People also ask

Can split () take two arguments?

split() method accepts two arguments. The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .

What is the advantage of splitting?

However, through share splits, a company can reduce its share prices and can make it more accessible to investors without changing its value whatsoever. Another one of the main stock split benefits is that the shares of a company generally see increased liquidity.

What happens when a company splits in two?

A split-up is a financial term describing a corporate action in which a single company splits into two or more independent, separately-run companies. Upon the completion of such events, shares of the original company may be exchanged for shares in one of the new entities at the discretion of shareholders.

What does 2 for 1 split mean?

If the stock undergoes a two-for-one split before the shares are returned, it simply means that the number of shares in the market will double along with the number of shares that need to be returned. When a company splits its shares, the value of the shares also splits.


1 Answers

(?!^) matches any position that's not at the start of the string, just as (?<!^). Since the ^ anchor doesn't have any length, it is irrelevant whether you look forward or backwards.

Imagine the string test like this where | denotes the positions between the characters:

|  t  |  e  |  s  |  t  |
^ matches here         ($ matches here)

(?!^) doesn't match at position 0 because the regex engine "sees" the start of string from here when looking forward by 0 characters

(?<!^) doesn't match here either because the regex engine "sees" the start of string from here when looking backwards by 0 characters

like image 156
Tim Pietzcker Avatar answered Oct 07 '22 16:10

Tim Pietzcker