Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular Expression to find a group of strings between two characters

Lets say I have:

[Radius: 4000 mi.] -- 61362 -- Spring Valley, IL, US

The aim is to get:

Spring Valley, IL

I want to achieve this with RegEx. When I try (?<=--)(.*?)(?=\, US) I can’t seem to get the second group of ‘–‘ out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the lookbehind, but in between you should not match -- again

(?<= -- )(?:(?! --).)*(?=, US)

Regex demo

const s = `[Radius: 4000 mi.] -- 61362 -- Spring Valley, IL, US`;
const regex = /(?<= -- )(?:(?! --).)*(?=, US)/;
const m = s.match(regex);
if (m) console.log(m[0]);

You can also use a capture group and make the match as specific as you want:

--\s+\d+\s+--\s+(.*?), US\b

Regex demo

const s = `[Radius: 4000 mi.] -- 61362 -- Spring Valley, IL, US`;
const regex = /--\s+\d+\s+--\s+(.*?), US\b/;
const m = s.match(regex);
if (m) console.log(m[1]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading