0

I need to get part of a string inside round brackets, for example the string could be:

FirstName LastName ( myemail@address.org )

I'm using the following code:

let string = 'FirstName LastName ( myemail@address.org )';
const regExp = /(([^()]*))/g;
let email = string.match(regExp);

When I try to get and print the email variable I get this:

FirstName LastName ,,myemail@address.org,,

What's wrong with my code? Thanks a lot for any help.

Alireza
  • 2,103
  • 1
  • 6
  • 19
Federico
  • 319
  • 2
  • 14
  • You have to escape special characters like `( )` when you don't want their special functions. – Andreas Aug 12 '21 at 09:48
  • 1
    Does this answer your question? [Regular Expression to get a string between parentheses in Javascript](https://stackoverflow.com/questions/17779744/regular-expression-to-get-a-string-between-parentheses-in-javascript) – Harun Yilmaz Aug 12 '21 at 09:49
  • 1
    @Andreas Um no...the parentheses are inside a character class and therefore don't need to be escaped. – Tim Biegeleisen Aug 12 '21 at 09:49
  • @TimBiegeleisen There are two sets of `(( ... ))` that are not part of the character class. Either one of them is useless or should be escaped – Andreas Aug 12 '21 at 09:51
  • @Andreas Pointless maybe...but they are just nested capture groups. Your comments are all wrong. – Tim Biegeleisen Aug 12 '21 at 09:53

1 Answers1

2

What's wrong with my code?

Your pattern is wrong and that is why you get the wrong result. probably you wanted to match everything except parentheses in your pattern((([^()]*))) but this match all strings that are outside of parentheses too, so that's why you get FirstName LastName ,,myemail@address.org,, based on your pattern output is actually right. this is everything except parentheses.

You can use this pattern: (?<=\().*?(?=\))

Explanation:

  • (?<=\() This is called positive lookbehind and look back for checking (not matching just checking) pattern inside it is in the back or not? if it is then continue the matching.

  • .*? Match everything zero or more times.

  • (?=\)) This is called positive lookahead and look ahead for checking (not matching just checking) pattern inside it is in the front or not? if it is then continue the matching.

So overall this pattern searching for a string that first starts with ( and then matches everything till that next char is ).

See Regex Demo

Code:

let string = 'FirstName LastName ( myemail@address.org )';
const regExp = /(?<=\().*?(?=\))/g;
let email = string.match(regExp);
console.log(email[0].trim());
Alireza
  • 2,103
  • 1
  • 6
  • 19
  • 1
    Not my DV, but when using `(?<=\().*(?=\))` the `.*` here will match till the last occurrence of `)` See https://regex101.com/r/07e8Si/1 I think it could be something like `\(\s*([^()]*?)\s*\)` or when it is an email `\(\s*([^\s@]+@[^\s@]+)\s*\)` – The fourth bird Aug 12 '21 at 18:30
  • 1
    Thank you @Thefourthbird, I updated my answer. – Alireza Aug 12 '21 at 18:33