0

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.

1
  • Just use (str.match(/.*--\s*(.*?),\s*US/) || ['', ''])[1] Commented Jun 28, 2022 at 19:28

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.