Splitting into multiple delimiters but keeping delimiters on one line

I need help with regular expressions to solve the following problem:

I have a string like "1 £ 23 $ 456 $ £ $"

when i split on it i want the output in my string array to contain:

1£
23$
456$
£
$

      

Does anyone know the best way to solve this problem? The solution must meet these additional requirements:

  • Also divide the characters separator: +

    , -

    , *

    and/

  • Non-delimited characters are just numbers with additional spaces in front of the delimiters.
  • Any such spaces are part of the value, not the delimiters themselves.
+3


source to share


3 answers


Use more powerful functionality Matcher

instead String.split

. The following code should work, but not optimized:

Pattern pattern = Pattern.compile("\\d*(\\$|£)");

String input = "1£23$456$£$";
Matcher matcher = pattern.matcher(input);
List<String> output = new ArrayList<>();
while (matcher.find()) {
    output.add(matcher.group());
}

      

The printout output.toString()

generates:

[1£, 23$, 456$, £, $]


Updated requirements:



  • Also include the separator characters: +

    , -

    , *

    and/

  • Non-delimited characters are just numbers with additional spaces in front of the delimiters.
  • Any such spaces are part of the value, not the delimiters themselves.

Use a regular expression: \\d*\\s*[-\\+\\*/\\$£]

This template with given input:

1£23$456$£$7+89-1011*121314/1 £23 $456 $ £ $7 +89 -1011 * 121314 /


Will generate this output:

[1£, 23$, 456$, £, $, 7+, 89-, 1011*, 121314/, 1 £, 23 $, 456 $, £, $, 7 +, 89 -, 1011 *, 121314 /]

+3


source


Use a look and feel that doesn't consume:

String[] parts = str.split("(?<=\\D)");

      

That's all. The regex means "immediately after each digit" separation, which seems to be your intention.




Some test codes:

String str = "1£23$456$£$";
String[] parts = str.split("(?<=\\D)");
System.out.println( Arrays.toString( parts));

      

Output:

[1£, 23$, 456$, £, $]

      

+2


source


You probably need this

Matcher m = Pattern.compile("[^$£]*(\\$|£)").matcher(input);

      

0


source







All Articles