-2

Let's say we have a string:

String x = "a| b |c& d^ e|f";

What I want to obtain looks like this:

a
|
b
|
c 
& 
d
^
e
|
f

How can I achieve this by using x.split(regex)? Namely what is the regex?

I tried this link: How to split a string, but also keep the delimiters?

It gives a very good explanation on how to do it with one delimiter. However, using and modifying that to fit multiple delimiters (lookahead and lookbehind mechanism) is not that obvious to someone who is not familiar with regex.

Community
  • 1
  • 1
user3277360
  • 127
  • 4
  • 3
    nice requirement doc....now you should move to implementation phase. – Juned Ahsan Jul 08 '15 at 23:09
  • 3
    I refuse to answer this because it's a) likely a duplicate, b) possibly homework, and c) contains no effort – Aify Jul 08 '15 at 23:09
  • Please post your attempt. And why don't you just split using a space as a delimiter? – sstan Jul 08 '15 at 23:09
  • never used regex before. I tried http://stackoverflow.com/questions/2206378/how-to-split-a-string-but-also-keep-the-delimiters but I want to split a string with different delimiters – user3277360 Jul 08 '15 at 23:17
  • Start here: http://www.regular-expressions.info/charclass.html – Pshemo Jul 08 '15 at 23:39

1 Answers1

2

The regex for splitsplitting on optional spaces after a word boundary is

\\b\\s*

Note that \\b checks if the preceding character is a letter, or a digit or an underscore, and then matches any number of whitespace characters that the string will be split on.

Here is a sample Java code on IDEONE:

String str = "a| b |c& d^ e|f";
String regex = "\\b\\s*";
String[] spts = str.split(regex);
    for(int i =0; i < spts.length && i < 20; i++)
    {
        System.out.println(spts[i]);
    }
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563