Regular Expression for Find and Replace?

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

  1. davedev100 macrumors member

    Jun 11, 2009
    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(){


    function 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

    Apr 1, 2007
    Something like this?


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


    Nov 25, 2005
    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 member

    Jun 11, 2009
    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

    Apr 1, 2007
    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

    Mar 8, 2009
    Denver, CO
    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

    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