Andy Stewart
Andy Stewart

Reputation: 5498

Regexp to match function calls

I am trying to write a regexp to match calls of autoloaded Vimscript functions. Autoloaded function names look like:

foo#bar()
foo#bar#baz()

They contrast with script-local calls which look like:

s:foo()

However I don't want to match function definitions, which look like:

function foo#bar()
function foo#bar#baz()

I started with a regexp to match function names:

(\w+(?:#\w+)+)\(

I.e. match foo#bar( or foo#bar#baz( and capture everything except the opening bracket.

Then I added a negative lookbehind to exclude function names preceded by function.

(?<!function )(\w+(?:#\w+)+)\(

However given function foo#bar() it matched oo#bar(.

So I added a word boundary:

(?<!function )\b(\w+(?:#\w+)+)\(

Now it correctly doesn't match function foo#bar() at all.

However given function foo#bar#baz() it matches bar#baz(. I can see why: the # after foo is a word boundary. Unfortunately I can't figure out how to get around this.

Any help would be much appreciated!

Upvotes: 2

Views: 383

Answers (2)

anubhava
anubhava

Reputation: 786081

In your negative lookbehind also add # to make sure you don't match from position just after #

(?<!\bfunction |#)(\b\w+(?:#\w+)+)

Also note use of word boundaries before function and before \w+ to avoid false matches.

RegEx Demo

Upvotes: 1

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this Regex:

^(?!function)\w+(?:#\w+)+(?=\()

Click for Demo

Explanation:

  • ^ - asserts the start of the line
  • (?!function) - negative lookahead to make sure that the current position is not immediately followed by function
  • \w+ - matches 1+ occurrences of a word-character(letters, digits and underscore)
  • (?:#\w+)+ - matches 1+ occurrences of a # followed by 1+ word characters
  • (?=\() - positive lookahead to make sure that the current position is followed by (

Upvotes: 1

Related Questions