Skip to content
Advertisement

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.

Advertisement

Answer

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+(.*?), USb

Regex demo

const s = `[Radius: 4000 mi.] -- 61362 -- Spring Valley, IL, US`;
const regex = /--s+d+s+--s+(.*?), USb/;
const m = s.match(regex);
if (m) console.log(m[1]);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement