Reputation: 319
I need to get part of a string inside round brackets, for example the string could be:
FirstName LastName ( [email protected] )
I'm using the following code:
let string = 'FirstName LastName ( [email protected] )';
const regExp = /(([^()]*))/g;
let email = string.match(regExp);
When I try to get and print the email variable I get this:
FirstName LastName ,,[email protected],,
What's wrong with my code? Thanks a lot for any help.
Upvotes: 0
Views: 701
Reputation: 2123
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 ,,[email protected],,
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 ( [email protected] )';
const regExp = /(?<=\().*?(?=\))/g;
let email = string.match(regExp);
console.log(email[0].trim());
Upvotes: 2