简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM