Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Regex to split a String

800282Nov 7 2008 — edited Nov 14 2008
Hi,

Here's a little regex problem Jos e-mailed me the other day, to which I didn't find a satisfactory answer (I found one, but it's rather verbose). Chances are that there is no short (or simple) solution, but when this is the case with a certain problem, I usually know why there is no simple solution because of some limitation with the regex flavor I am using. However, I can't think of one with this problem.

Also note that this problem can be easily (and far more efficiently) solved by writing a custom method, but I happen to like regex and am curious to know if there's some solution to this I missed.

So, without further a due, here is the questions:

Split a String T into parts with a maximum size N without splitting T on a certain sub string S. In other words: try to split a String in as large as possible parts (equal or less than N) without splitting it on a certain sub string.
You can use only one split(...) call!

Lets say
 S = abc
and
 N = 5 
then here are a couple of examples:
T            = xyabcdefgabc
T.split(...) = [xyabc, defg, abc]

T            = xyzabcbbzzzabcabcbcacbyyy
T.split(...) = [xyz, abcbb, zzz, abc, abcbc, acbyy, y]

T            = xyzzzzabcbabczabcabcabcacbyyy
T.split(...) = [xyzzz, zabcb, abcz, abc, abc, abcac, byyy]
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 12 2008
Added on Nov 7 2008
17 comments
277 views