Regular Expression for Find and Replace?

Discussion in 'Mac Programming' started by davedev100, Aug 24, 2011.

  1. davedev100 macrumors newbie

    Joined:
    Jun 11, 2009
    #1
    How would I create a regular expression to find and replace all the functions declarations in an class file with a copy of the function declaration and then a call to object passing the function name for debugging purposes.

    For example, I'd want to replace

    function showSkittles(){

    with

    function showSkittles(){
    debugObject.traceFunction("showSkittles");


    Pseudo expression code would look like this:


    Find ("<>" enclose variables):

    "public function" + <function name> + "}"

    Replace with:

    <found string> + line break + "debugObject. traceFunction(" + <function name> + ");"
     
  2. Hansr macrumors 6502a

    Joined:
    Apr 1, 2007
    #2
    Something like this?

    "function\W*([^\(\W])\(\)\{\n"

    "function $1(){\ndebugObject.traceFunction("$1");\n"
     
  3. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #3
    Don't do that. Look up in the compiler manuals what macros exist that evaluate to the function name. Like __func__ .
     
  4. davedev100 thread starter macrumors newbie

    Joined:
    Jun 11, 2009
    #4
    gnasher729, thanks for the suggestion. I'm working in ActionScript so the function name is not available. You can get a reference to the function but not the function name.

    ----------

    Hansr, thanks for the regex. Can you give a brief explanation? It fails after "function\W*" for me and I don't know enough to figure it out.
     
  5. Hansr macrumors 6502a

    Joined:
    Apr 1, 2007
    #5
    Regex find and replace is implemented differently for each text editor/IDE but basically it's:


    function <- the word function
    \W* <- one or more whitespace characters
    ([^\(\W]) <- match anything not ( nor whitespace, e.g. function name
    \(\) <- brackets ()
    \{\n <- open curly brackets + linebreak

    The replace works the same way but $1 will contain the match.
     
  6. jpyc7 macrumors 6502

    Joined:
    Mar 8, 2009
    Location:
    Denver, CO
    #6
    Based on Hansr's explanation, I would guess that the specification of whitespace characters is different for your regex processor.

    Two other common ways of specifying a whitespace character are:
    \S or \s
    [:space:]

    The latter is supposedly the POSIX standard, but sometimes you need extra square brackets on both sides because the regex processor treats square bracket characters specially too.
     

Share This Page