Home > Mobile >  Regular Expression to find a group of strings between two characters
Regular Expression to find a group of strings between two characters

Time:06-29

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.

CodePudding user response:

If you're open to considering a non-regex approach, you can split the string on the hyphens and spaces (' -- '), take the element at index 2 (the city, state, country), split that by the comma limiting the results to 2, and then rejoining by a comma, and you have what you're looking for.

Easier to read than a regex approach, and likely easier for other developers in your code base to understand what is happening.

const s = '[Radius: 4000 mi.] -- 61362 -- Spring Valley, IL, US';

const cityState = s.split(' -- ')[2]?.split(',', 2).join(',');

console.log(cityState);

CodePudding user response:

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]);

  • Related