Home > Net >  How to match all func parameters in regex with the func name
How to match all func parameters in regex with the func name

Time:06-21

My code below matches all func parameters without the func name:

(?<=\(|\,)\s*([a-zA-Z] )\s*(?=\:|\s*)

How can I add a condition to match the func name and its parameters only if there is a "func" keyword? enter image description here

Edited: Working with the code written by @tukan:

((?<=func\s)\w )|(\w (?=:))

text code to test:

func foo(a: Int, b: String = "myStr", c: Double)

func foo(a s1: Int, b s2: String = "myStr", c: Double = 1.0)

func     foo(a: Int, b: String, c: Double = 3343)

func foo()

enter image description here

CodePudding user response:

Edit: answer due to OP update

You can not do a programming language parser with regexp that is nonsense! You would have to create yourself a custom parser for that.

In this answer I'm using PCRE 8.40-8.45 UTF-8.

To parse your updated question:

(\w (?=\())|((?<=\()\s*\w )|((?<=,\s)\w )

  • First part is matching the function name.
  • Second part is for the first parameter right after the bracket.
  • Third part is for the parameters that are not at the beginning.

Regex demo

CodePudding user response:

You could make use of 2 capture groups and the \G anchor

 (?:\b(func)\s \w \(|\G(?!^)(?::\s*\w )?,\s*)(\w )

The pattern matches:

  • (?: Non capture group
    • \b(func)\s \w \( Capture func in group 1
    • | Or
    • \G(?!^) Assert the current position at the end of the previous match, but not at the start of the string (as \G can match at both positions)
    • (?::\s*\w )?,\s* Optionally match a colon, optional spaces, then a comma and optional spaces
  • ) Close the non capture group
  • (\w ) Capture 1 word chars in group 2

Regex demo

  • Related