Home > Back-end >  Regex to find a word that is not followed by two more words inside brackets
Regex to find a word that is not followed by two more words inside brackets

Time:06-30

I am attempting to add a rule to code linting that would require all of my functions to have a input parameters type specified. These are some different options I am able to compile:

function someName()
function someName(someParam)
function someName(someParam as int)
function someName(someParam = "" as int)
function someName(someParam = "")
function someName(someParam, otherParam)
function someName(someParam as int, otherParam)
function someName(someParam, otherParam as int)
function someName(someParam as int, otherParam as int)

But I want to match these as invalid:

function someName(someParam)
function someName(someParam = "")
function someName(someParam, otherParam)
function someName(someParam as int, otherParam)
function someName(someParam, otherParam as int)

So, I want all cases where any of input parameters not have as <some text> to be matched

In these examples, I can use:

function \w \(.*Param(?! (= .*|)as \w ).*\)

but I cannot figure out how to make it work with any input parameter name

I am fine with multiple passes to match different invalid cases, as long as they do not match valid ones

CodePudding user response:

You can use this regex to find all valid matches:

function\s \w \((?:\s*\w \s as\s \w (?:\s*,\s*\w \s as\s \w )*)?\s*\)

RegEx Demo

Any line not matching above regex will be considered an invalid match.

RegEx Details:

  • function\s \w : Match function followed by name of the function
  • \(: Match starting (
  • (?:: Start optional non-capture group
    • \s*\w \s as\s \w : Match first parameter that must have associated type
    • (?:\s*,\s*\w \s as\s \w )*: Match comma followed by another parameter that must have associated type. Repeat this group 0 or more times to match all such parameters
  • )?: End optional non-capture group
  • \s*: optional whitespaces
  • \): Match closing )

If you only want to find invalid matches then use:

function\s \w \((?!(?:\s*\w \s (.*?)as\s \w (?:\s*,\s*\w \s (.*?)as\s \w )*)?\s*\))

RegEx Demo 2

  • Related