So I have a problem and this is my first time asking within this community, so please be gentle. I am trying to extract a string within another string but the problem is that the end string has parentheses and that is messing with the regular expression. I am trying to capture the company name, "SMITH PSYCHIATRIC, INC." using "of" and ("Customer") as the beginning and end anchors.
My sample is:
I, Fred Smith, HEREBY CERTIFY that I am MD of SMITH PSYCHIATRIC, INC. ("Customer"), an entity organized under the laws of the State of CA.
I was trying to use (?<=of).*(?=("Customer")) but the parentheses of ("Customer") is messing with the regular expression.
I did try to excape the parentheses like (?<=of).*(?=\("Customer"\)) but it still comes back invalid.
Thank you for your help.
CodePudding user response:
Welcome to SO, Andrew. You can follow the below code pattern to get what you need.
String Object :
I, Fred Smith, HEREBY CERTIFY that I am MD of SMITH PSYCHIATRIC, INC. ("Customer"), an entity organized under the laws of the State of CA.
You need :
"SMITH PSYCHIATRIC, INC."
You can follow this code :
"use strict";
const stringObj =
'I, Fred Smith, HEREBY CERTIFY that I am MD of SMITH PSYCHIATRIC, INC. ("Customer"), an entity organized under the laws of the State of CA.';
// let pattern = /(?<=of).*(?=("Customer"))/;
let pattern = /(?<=of ).*(?=\s[(])/;
//output : SMITH PSYCHIATRIC, INC.
console.log(pattern.exec(stringObj)[0]);
Pattern description : get the matching characters between "of" and " (". Note the space before "(". In case, there is no space in the string object, you can remove the "\s" in the pattern.
CodePudding user response:
You are right about escaping the parenthesis. You can use a capture group without lookarounds, and get the group 1 value:
\bof\s (.*?)\s*\("Customer"\)
const s = 'I, Fred Smith, HEREBY CERTIFY that I am MD of SMITH PSYCHIATRIC, INC. ("Customer"), an entity organized under the laws of the State of CA.';
const regex = /\bof\s (.*?)\s*\("Customer"\)/;
const m = s.match(regex);
if (m) console.log(m[1]);