0

Possible Duplicate:
How do I split a string by strings and include the delimiters using .NET?

I have following code:

string Test="abc * (xyz+ pqr) - 10/100";

char[] delimiters = new char[] { '+', '-', '*', '/', '(', ')' };
string[] parts = Test.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
    Response.Write(parts[i]);
}

I m getting output as:

abc xyz pqr 10100

But i want:

abc
*
(
xyz
+
pqr

...and so on.

(in c# or in javascript)

Community
  • 1
  • 1
rach
  • 669
  • 2
  • 8
  • 31
  • If you're outputting to HTML, you need to make sure you're adding break tags
    after each element you're printing or they'll all stay on the same line.
    – beezir Jan 14 '13 at 16:21
  • 1
    Try this: http://stackoverflow.com/questions/2484919/how-do-i-split-a-string-by-strings-and-include-the-delimiters-using-net?rq=1 – Matthew Jan 14 '13 at 16:22
  • 1
    This may also help: http://stackoverflow.com/questions/521146/c-sharp-split-string-but-keep-split-chars-separators – Tyler Lee Jan 14 '13 at 16:30

2 Answers2

2

In JavaScript, you can use capturing groups of a regex:

var test = "abc * (xyz+ pqr) - 10/100";

var regex = /\s*([()*/+-])\s*/;
var parts = test.split(regex);
for (var i = 0; i < parts.length; i++)
    document.writeln(parts[i]);

Yet this does not work in older Internet Explorers, you would need to do it manually there or use this shim. Better, cross-browser solution: Just match variable names and numbers as well, and use match:

var regex = /[()*/+-]|[a-z]+|\d+/g;
var parts = text.match(regex);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I want the maths signs (+,-,(,),*,/,) also. its printing only abc xyz pqr 10 100 – rach Jan 14 '13 at 16:29
  • No. It prints `abc * ( xyz + pqr ) - 10 / 100` unless you use a non-supporting browser (notice the empty strings between two delimiter). – Bergi Jan 14 '13 at 16:32
-1
//Change this line
char[] delimiters = new char[] { '+', '-', '*', '/', '(', ')' };

//Change it to
char[] delimiters = new char[] { ' ' };

;

Raghavan
  • 637
  • 3
  • 12