Reputation: 1831
I have a Python module and I want to catch all it's public methods, no private or child methods, for example,
def Func1(c, v1=None, v2=None, v3=None):
def childFunc(c): # I don't want to catch this
This is my regular expression:
/def ([a-zA-Z]\w+\([\w, =]+\)):/
However this also matched the child methods as well and it doesn't work on definitions that spanned multiple lines:
def Func2(c, v1=None, v2=None, v3=None, \
v4=None, v5=None):
Upvotes: 1
Views: 138
Reputation:
This does not only catch the function definition (like the other answers) but the whole function.
^def \w+\([^\f\v\r\n]*?\)\:[\s\S]+?^(?![ \t#])
explanation;
^def
matches the beginning of a line followed by a "def" and a space " ".
\w+
matches the name of the function.
\([^\f\v\r\n]*?\)\:
matches a parenthesis containing anything that is not the beginning of a new line (lazy), followed by ":".
[\s\S]+?
matches absolutely anything (lazy).
^
matches the beginning of a line.
(?![ \t#])
requires that the next thing is not a space, tab or beginning of a comment.
Upvotes: 0
Reputation: 18641
Use
(?m)^def ([a-zA-Z]\w*)\(([^()]*)\):
See proof
NODE | EXPLANATION |
---|---|
^ |
the beginning of the string |
def<SPACE> |
'def ' |
( |
group and capture to \1: |
[a-zA-Z] |
any character of: 'a' to 'z', 'A' to 'Z' |
\w* |
word characters (a-z, A-Z, 0-9, _) (0 or more times (matching the most amount possible)) |
) |
end of \1 |
\( |
'(' |
( |
group and capture to \2: |
[^()]* |
any character except: '(', ')' (0 or more times (matching the most amount possible)) |
) |
end of \2 |
\) |
')' |
: |
':' |
Upvotes: 2
Reputation: 6063
Trying to keep out child functions in any other language that uses opening and closing braces would quickly become a nightmare just using regex. But in Python it actually seems doable. Try this:
^(?:\t| {4})def ([a-zA-Z]\w*\([^:]*\)):
The 4
represents how many spaces you are using for one indented line, so change it as needed.
Upvotes: 0