I am large set of array from which I am trying to find the address
For example this(State Code :- CO)
0 Site Address, San Luis, CO 81152
Now to match this I am using this regex expression :-
e.match(/, CO \d/)
How can I incorporate many statecode in it like if I have to check for this(State Code :- NM)
2 X Valley Rd X P2, Questa, NM 87556
Any address state code can come, so I want it to dynamic to check all the state codes
Please suggest
CodePudding user response:
The most basic way to capture any state code would be to include a capture group with all the values you need to match.
Ex:
e.match(/, (CO|NM|TN|MO) \d/)
Wrap the different state options in parentheses, and use the pipe symbol to indicate "or".
If you have all the state codes in an array you could dynamically create this capture group.
ex:
const states = [
"TN",
"NM",
"CO",
]
const regexStr = states.join("|")
const stateMatch = new RegExp(`, (${regexStr}) \d`)
e.match(stateMatch)
CodePudding user response:
You can try with the following regex:
, [A-Z]{2} \d{5}
It checks for symbols in the following succession:
,
: a comma a space[A-Z]{2}
: two letters\d{5}
: five digits
This approach will generalize on the state codes.