问题描述:

I'm trying to find a regular expression for "def"

it should work as following:

def h():

def f(a=1):

def g(a=-2):

def x(_sad,sda_,m=+3, n=-2):

cases it don't work:

def (m, x=y)

what I did:

^def\s\w+\((\w\,)*(\w+=?\+?\-?\d+\,)*(\w)*\):$

However, it doesn't pass the case "def f(a=1):" and "def g(a=-2):"

Where I did wrong??

My object here is to fulfill these cases:

def h():

def f(a=1):

def g(a=-2):

def x(_sad,sda_,m=+3, n=-2):

and not fulfill these cases:

def (m, x=y)

网友答案:

Just for fun

\s*def\s+[^\(]+\([^\)]*(?:(?:\([^\)]*?\))[^\)]*)*\):

Regex demo

Explanation:
^: Start of string or start of line depending on multiline mode
\s: "whitespace character": space, tab, newline, carriage return, vertical tab sample
+: One or more sample
\w: "word character": ASCII letter, digit or underscore sample
*: Zero or more times sample

Input:

def h():
def f(a=1):
def g(a=-2):
def x(_sad,sda_,m=+3, n=-2):
def (m, x=y) 
def name(database_name):
    def name(name1, name2):
        def name(name1, attr=value):
    def name(name1, default='', length=default, **value):
    def name(name1, default='', length=(0, 999), **kwargs):

Match all except def (m, x=y)

相关阅读:
Top