Searching code with grep

Imagine you’re working on your software project and need to find a function or class definition, or all references. Maybe that’s why you’re here.

Though there are faster and more powerful alternatives to grep, it has the advantage of being readily available on most machines and having familiar syntax.

This page lists common regexes for top programming languages. Is your language missing here? Send us a comment.

Note: some of the programming languages below have an irregular grammar, which means perfectly searching for certain attributes with a regular expression is not always possible.

Replace ‘yourfunction’ or ‘YourClass’ below with whatever you are trying to find.


    # search for function definitions
    grep -r code_folder "def yourfunction"

    # search for class definitions
    grep -r code_folder "class YourClass"
    # Note, Javascript syntax is highly irregular. Unless your project enforces
    # strict formatting rules, you will likely have trouble grepping for code.

    # search for function definitions
    # classic js style, ex: function test() {
    grep -r code_folder "function yourfunction"
    # classic js, assignment style, ex: test = function() {
    grep -r code_folder "yourfunction[[:space:]]*=[[:space:]]*"
    # ES6 style functions, ex: x = (args) => {
    # especially problematic for grep as the line may be broken up
    grep -r code_folder "yourfunction[[:space:]]*=(.*)[[:space:]]*=>"

    # search for class definitions
    # classic js, ex: class YourClass
    grep -r code_folder "class YourClass"
    # expression style, ex YourClass = class 
    grep -r code_folder "class YourClass"
    # function definitions
    # matches both bare functions, ex: func yourfunction
    # And
    # Methods / member functions, ex func (f Object) YourFunction()
    grep -r code_folder "func.*yourfunction("