locked
find function in string with Regex

    Question

  • Hi!

    I have a string that may contain functions. Example: "3+Sqrt(2x)-1".

    First I thought of sth. like

    Regex functionHead = new Regex(@"[A-Z][a-z]+\(.*\)");   

    But then I remebered that a function may contain other functions. Example: "3+Sqrt(Wohow(2x))-1". With my first idea
    Sqrt(Wohow(2x) would have been a function, which is wrong of course, as only Sqrt(Wohow(2x)) is a function.

    I seriously don't know how to solve this problem.

    Please save a poor German's life!

    • Moved by Peter RitchieMVP, Moderator Friday, August 22, 2008 8:44 PM Regex question (Moved from Visual C# General to Regular Expressions)
    Friday, August 22, 2008 5:46 PM

All replies

  • This thread is highly related to what you ask...

     http://forums.msdn.microsoft.com/en-US/regexp/thread/529fdf44-2494-4a16-ae93-a166a94c1da6

    See if it helps you over the hump.  Also, I couldn't find it right off, but there are similar discussions in the last couple of months on the same subject under the Regex Forum.


    Les Potter, Xalnix Corporation, Yet Another C# Blog
    Friday, August 22, 2008 6:12 PM
  • what about a regex that returns functions at the beggining of the string:


    ^[a-zA-Z0-9]+\(

    or functions that dont begin the expression but follow an operator:

    [\+\*\\\^\-]{1}[a-zA-Z0-9]+\(

    or functions that are nested within functions:

    \([a-zA-Z0-9]+\(

    or functions that are nested within functions having 2 or more parameters

    [\(|,]{1}[a-zA-Z0-9]+\(

    string them together using or's and grouping:

    (^[a-zA-Z0-9]+\()|([\+\*\\\^\-]{1}[a-zA-Z0-9]+\()|(\([a-zA-Z0-9]+\()|([\(|,]{1}[a-zA-Z0-9]+\()

    That is long enough, but you could also put in non-capturing construct to avoid returning the various characters that dont belong as part of the function.

    Otherwise, your match will be:

    +Sqrt(

    which isnt a big deal because basically, you only match 1 character before the function and one character after. That's enough to let you know where the function begins:

    match.index + 1

    and where the match ends

    match.index + match.length

    Btw, i'm also working on regex with calculator expressions. fun stuff, eh?








    Monday, August 25, 2008 2:33 PM