Code
Python function definition Regex
Python functions are declared with def, a name, a parameter list in parentheses and a closing colon. Modern code may add async before def and a return annotation after an arrow. This pattern matches a complete single-line definition, with any indentation so it also finds methods inside classes. It is useful for quick code statistics, generating outlines of a module and pre-commit checks for naming rules. It does not handle signatures that span several lines, which are common with many parameters, and it does not check that the parameter list itself is valid. Use the ast module for exact results.
Pattern (JavaScript)
/^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$/Starts at the start of the line/string, then a whitespace character (space, tab, newline), zero or more times, then (the text "async", then one or more whitespace characters), optionally (zero or one time), then the text "def", then one or more whitespace characters, then one of the characters A-Za-z_, then a word character (letter, digit or underscore), zero or more times, then a whitespace character (space, tab, newline), zero or more times, then the character "(", then any character, zero or more times, then the character ")", then a whitespace character (space, tab, newline), zero or more times, then (the text "->", then a whitespace character (space, tab, newline), zero or more times, then any character except :, one or more times), optionally (zero or one time), then the character ":", then a whitespace character (space, tab, newline), zero or more times, then the end of the line/string.
Examples
Matches
- ✓ def greet(name):
- ✓ async def fetch_data(url: str) -> dict:
- ✓ def _helper() -> None:
Does not match
- ✗ define(x):
- ✗ def 2bad():
- ✗ def greet(name)
- ✗ function greet() {}
Try it
0 matches (JavaScript engine)
def greet(name):
async def fetch_data(url: str) -> dict:
def _helper() -> None:
define(x):
def 2bad():
def greet(name)
function greet() {}Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$/g;
const text = "def greet(name):";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$')
text = 'def greet(name):'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$/';
$text = 'def greet(name):';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^\\s*(?:async\\s+)?def\\s+[A-Za-z_]\\w*\\s*\\(.*\\)\\s*(?:->\\s*[^:]+)?:\\s*$");
String text = "def greet(name):";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$`)
text := "def greet(name):"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$");
var text = "def greet(name):";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$").unwrap();
let text = "def greet(name):";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\s*\(.*\)\s*(?:->\s*[^:]+)?:\s*$/
text = 'def greet(name):'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- How do I capture the function name?
- Wrap [A-Za-z_]\w* in a capture group. With the g and m flags you can run the pattern over a whole file and list every function and method name.
- Why does indentation not matter?
- The leading \s* allows any indentation, so methods inside classes and nested functions also match. Remove it if you only want top-level functions.
- What about definitions that span several lines?
- Long signatures are often wrapped over many lines, and this single-line pattern will miss them. Python's ast module parses every form reliably and gives you names and arguments directly.