Question on Regex.Split

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Frank Oquendo

    Question on Regex.Split

    I have the following code:

    string pattern =
    @"(\{)|(})|(\() |(\))|(\[)|(])|(\^)|(\*)|(/)|(-)|(\+)|(%)";
    Regex regex = new Regex(pattern);
    string input = "QTY * ESTIMATED COST + 2";
    string[] tokens = regex.Split(inp ut);
    for (int i = 0; i != tokens.Length; i++)
    {
    Console.WriteLi ne("Token {0} = {1}", i, tokens[i].Trim());
    }
    Console.ReadLin e();

    According to the documentation on the Split function, the returned
    string array will include the captures if I use capturing groups. IOW, I
    should get an array containing 5 elements. Instead I'm only getting
    three (QTY, ESTIMATED COST and 2). What am I doing wrong?

    --
    There are 10 kinds of people. Those who understand binary and those who
    don't.


    (Pull the pin to reply)


  • Frank Oquendo

    #2
    Re: Question on Regex.Split

    Never mind. I changed my pattern to the following and it works as
    expected now.

    string pattern = @"([-\+%\*\^\{}\(\)\[\]])";

    --
    There are 10 kinds of people. Those who understand binary and those who
    don't.


    (Pull the pin to reply)


    Comment

    • Brian Davis

      #3
      Re: Question on Regex.Split


      Wrap the entire expression in (...) instead of each alternative:

      (\{|}|\(|\)|\[|]|\^|\*|/|-|\+|%)


      Brian Davis




      "Frank Oquendo" <franko@acadxpi n.com> wrote in message
      news:Ot9IrqWqDH A.644@TK2MSFTNG P11.phx.gbl...[color=blue]
      > I have the following code:
      >
      > string pattern =
      > @"(\{)|(})|(\() |(\))|(\[)|(])|(\^)|(\*)|(/)|(-)|(\+)|(%)";
      > Regex regex = new Regex(pattern);
      > string input = "QTY * ESTIMATED COST + 2";
      > string[] tokens = regex.Split(inp ut);
      > for (int i = 0; i != tokens.Length; i++)
      > {
      > Console.WriteLi ne("Token {0} = {1}", i, tokens[i].Trim());
      > }
      > Console.ReadLin e();
      >
      > According to the documentation on the Split function, the returned
      > string array will include the captures if I use capturing groups. IOW, I
      > should get an array containing 5 elements. Instead I'm only getting
      > three (QTY, ESTIMATED COST and 2). What am I doing wrong?
      >
      > --
      > There are 10 kinds of people. Those who understand binary and those who
      > don't.
      >
      > http://code.acadx.com
      > (Pull the pin to reply)
      >
      >[/color]


      Comment

      Working...