-1

We tried many forms of regular expressions in this answer. Our input string is

"string1 & string2 / string3"

and we would like to split it into the string into

{"string1","string2","string3"}

on the delimiters & and / (with one space of padding for each).

How can we construct a regular expression to do this using string.split(" [/&] ")?

Community
  • 1
  • 1
craastad
  • 6,222
  • 5
  • 32
  • 46

6 Answers6

1

Didn't got ur question correctly, what you have mentioned is perfectly ok.

And if you want this :: {"string1","string2","string3"}

simply do : System.out.println( "{\"" + s.replaceAll( " [/&] ", "\",\"") + "\"}" );

Devarsh
  • 116
  • 3
0

Try the below one.

String[] result = string.split(" & | / ");

Hopes this helps.

ѕтƒ
  • 3,547
  • 10
  • 47
  • 78
0

Try this:

String[] split = s.split("[&//] ");
Gilad Shahrabani
  • 706
  • 1
  • 6
  • 12
0
    for (String part : "string1 & string2 / string3".split(" [/|&] ")) {
        System.out.println(part);
    }

So what you're interested in is the .split(" [/|&] ") part

Gabriel Ruiu
  • 2,753
  • 2
  • 19
  • 23
0

Just try with

String input = "string1 & string2 / string3";
boolean first = true;

StringBuilder sb = new StringBuilder("{\"");

for (String part : input.split(" [&/] ")) {
    if (!first) {
        sb.append("\",\"");
    }
    sb.append(part);
    first = false;
}

String output = sb.append("\"}").toString();

Output:

{"string1","string2","string3"}
hsz
  • 148,279
  • 62
  • 259
  • 315
0

Your code runs just fine.

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {

    String str = "string1 & string2 / string3";
    String delimiters = " [/&] ";

    // analyzing the string
    String[] tokensVal = str.split(delimiters);

    // prints the number of tokens
    System.out.println("Count of tokens = " + tokensVal.length);

    for(String token : tokensVal) {
       System.out.println("#" + token + "#");
    }
  }
}
Yosep Kim
  • 2,931
  • 22
  • 23