Hitesh Bavaliya
Hitesh Bavaliya

Reputation: 941

Need to split string(formula) with specified pattern

i need to split the following string into mentioned pattern

String str = "([myString1 - L]*[myString2 - L])/([myString3 - D]+[myString4 - N])";

and i want the output like following lines:

1. (
2. [myString1 - L]
3. *
4. [myString2 - L]
5. )
6. /
7. (
8. [myString3 - D]
9. +
10. [myString4 - N]
11. )

Upvotes: 0

Views: 343

Answers (3)

poy
poy

Reputation: 10507

This looks to me like you're trying to parse an equation... (perhaps to then use with the Shunting-yar algorithm :) So really, you want to break up the equation into 3 categories:

  1. Operators (*,/,+,- ...)
  2. Operands ([myString1 - D]
  3. Parentheses

To use regular expressions, I would google it... there are many resources, but the cheat sheet I use is: http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet

It has most of the operations you're wanting.

Each category I described above should be it's own group. You would then want to or them together.

This gives us:

(<?operator>[\+\-\*\/])|(<?operand>\w\s\-\[LD])|(<?par>[\(\)])

This will return one match per part. So you would just want to keep cycling until you don't have any more matches.

Upvotes: 1

Bob Vale
Bob Vale

Reputation: 18474

Well matching on what you've specified you could try

new Regex(@"(?<=[(*/+)])(?=.)|(?<=.)(?=[(*/+)])").Split(str);

This will match

  • either preceding char is *, /, (, ) or + and the next character exists
  • or next char is *, /, (, ) or + and the preceding character exists

You need that preceding/next character exists check otherwise it will split at the beginning / end of your string.

Upvotes: 1

sloth
sloth

Reputation: 101072

I agree with neoistheone that this looks like a job for a parser, but nonetheless you could use a regex like

var str = "([myString1 - L]*[myString2 - L])/([myString3 - D]+[myString4 - N])";
var result = Regex.Split(str, @"(\[[^]]+\]|[/\*\+\(\)])").Where(r => r != "").ToList();

which will give you the output you want (as long as your input stays that simple, e.g. no nested expressions in your input).

Upvotes: 2

Related Questions