mwebber mwebber - 2 months ago 11
Javascript Question

Javascript Regex comma separated text

I have this string:

remote:City|Vestavia Hills,AL,remote:Citystate|Vestavia Hills,395b5231539390675a7abe0751fc4820,remote:City|Vestavia Hills,AL,remote:Citystate|Vestavia Hills,395b5231539390675a7abe0751fc4820


I want to match and extract strings separated with commas.

The result should be:

MATCH 1
'remote:City|Vestavia Hills,AL'
MATCH 2
'remote:Citystate|Vestavia Hills'
MATCH 3
'395b5231539390675a7abe0751fc4820'
MATCH 4
'remote:City|Vestavia Hills,AL'
MATCH 5
'remote:Citystate|Vestavia Hills'
MATCH 6
'395b5231539390675a7abe0751fc4820'


I have this regex:

(remote:[a-zA-Z]+\|[^\,]+|[a-f0-9]{32})


but those cities which have state 'AL' (separated with comma) are separated incorrectly.

Possible solution:

I was thinking of doing something like this -
remote:[a-zA-Z]+\|.*
- and end match on the comma which have after it self (
remote:[a-zA-Z]+\|.*
) or md5 hash (
[a-f0-9]{32},?
).

Here is my regex tester link:

https://regex101.com/r/rP8iJ2/1

Answer

With a single regex you might do as follows;

var str = "remote:City|Vestavia Hills,AL,remote:Citystate|Vestavia Hills,395b5231539390675a7abe0751fc4820,remote:City|Vestavia Hills,AL,remote:Citystate|Vestavia Hills,395b5231539390675a7abe0751fc4820",
    arr = str.match(/(r.+?|[\da-f]{32})(?=,?(remote|[\da-f]{32}|$))/g);
console.log(arr);

Comments