Reputation: 1629
I have an address like this:
123 Main St, Los Angeles, CA, 90210
I'd like to capture just the city:
Los Angeles
I've beeing trying tomsething like this:
(?:[^,]+),\s([^,]+)
But I don't understand how to return just the 2nd group. Using a flag like {2} seems to be including every up to the second group and not only the second group.
UPDATE
I'm using a Chrome extension that uses regex patterns, so using Javascript or another language is not possible in this case.
Upvotes: 2
Views: 1295
Reputation: 12438
Why do you need a regex for this? A split should be enough.
Example in JS:
var str = "123 Main St, Los Angeles, CA, 90210";
var res = str.split(", ");
if(res.length>1)
{
console.log(res[1]);
}
Example in Python:
s = "123 Main St, Los Angeles, CA, 90210";
r = s.split(", ")
if len(r) > 1:
print(r[1])
Example in Java:
String s = "123 Main St, Los Angeles, CA, 90210";
String[] parts = s.split(", ");
if(parts.length > 1)
{
System.out.print(parts[1]);
}
Upvotes: 1
Reputation: 27723
My guess is that maybe this expression might be of interest here,
(?<=,\s)([A-Z].*?)(?=[,\s]*[A-Z]{2}[,\s]*\d{5}(?:-\d{4})?)
If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
Upvotes: 1
Reputation: 520978
A general pattern you may try is:
^[^,]+,\s*([^,]+)
The city name would be available in the first (and only) capture group.
Upvotes: 2