-3

My code below match the first word after one expression "let" :

(?<=\blet\s)(\w+)

What I need is to match the first word after a specific expressions, "let", "var", "func"

Input text:

let name: String
var age: Int
func foo() {
//...

Expected:

name
age
foo

Here is an image for clarity: enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Hassan Taleb
  • 2,350
  • 2
  • 19
  • 24

1 Answers1

2

Since some regex flavors do not allow using groups inside lookbehinds and alternatives of different length, it is safe to use a non-capturing group with the lookbehind as alternatives:

(?:(?<=\blet\s)|(?<=\bvar\s)|(?<=\bfunc\s))\w+

Here, (?:...|...|...) is a non-capturing group matching one of the three alternatives: (?<=\blet\s), (?<=\bvar\s) and (?<=\bfunc\s).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • This is a really nice trick. Using an alternation of lookbeinds instead of a lookbehind of alternation, to bypass the "variable length lookbehind" problem. – WhiteMist Jun 18 '22 at 14:11
  • If variable-length lookbehinds are supported: `(?<=\b(?:let|var|func)\s)\w+` – MikeM Jun 18 '22 at 14:33