find function in string with Regex


  • 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...


    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:


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


    or functions that are nested within functions:


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


    string them together using or's and grouping:


    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:


    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