Get Off My Lawn Get Off My Lawn - 1 year ago 61
Javascript Question

Find word before opening parenthesis

I have the following line of code:

let regexp: RegExp = new RegExp('(?=\\s(.+))');

What I am trying to do is find the word that comes before a
in a code file.

With what I have, it matches more than what I would like.

this is a test (

Matches :
is a test (
I just want


No matches were found.

So, how can I get the word that comes before the parenthesis?

Answer Source

The (?=\\s(.+)) regex matches an empty location (because the whole pattern presents a positive lookahead, a zero-width assertion consuming no characters) that is followed with 1 whitespace and 1+ any characters other than a newline (that are captured into Group 1). Thus, it may match more than one word.

You can use




See the regex demo

Pattern explanation:

  • \w+ - 1 or more word chars (or 1+ non-whitespace chars if \S+ is used)....
  • (?=\s*\() - before 0+ whitespaces (\s*) followed with a literal ( char (or before 1+ whitespaces followed with a ( if (?=\s+\() is used).

var re = /\w+(?=\s*\()/; 
var str = 'this is a test (';
var res = (m = str.match(re)) ? m : "";

Alternative: Capturing Groups

You can achieve the same without any lookarounds. I like lookaheads since they are not that costly in most cases and the match structure is cleaner (you just have a single group equal to the whole match), but in this scenario, a mere capturing mechanism can be leveraged with


where the value we need is captured with (\w+), a parenthesized part of the pattern. See the regex demo

var re = /(\w+)\s*\(/; 
var str = 'this is a test (';
var res = (m = str.match(re)) ? m[1] : "";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download