Tomster
Tomster

Reputation: 64

Extract with regex when the same special character is used

I've been trying to use Regex tools online, but none seem to be working. I am close but not sure what I'm missing.

Here is the Text:

Valencia, Los Angeles, California - Map

I want to extract the first 2 letters of the state (so between "," and "-"), in this case "CA"

What I've done so far is:

[,/](.*)[-/]
$1

The output is:

Los Angeles, California

If anything I thought I would at least just get the state.

Upvotes: 0

Views: 24

Answers (4)

Tim Cooke
Tim Cooke

Reputation: 872

,\s*(\S{2})[^,]*-

You're going to want to take just the first match.

Upvotes: 1

Maroun
Maroun

Reputation: 95968

You can use this regex:

.*?,\s(\w\w)[^,]*-

$1 is the first two letters you're looking for.

Upvotes: 0

Cristian Lupascu
Cristian Lupascu

Reputation: 40546

I assume you use JavaScript.

Your regex fails this particular case because there are two commas in your input.

One possible fix is to modify the middle capture from . (any character) to [^,] (any character except comma). This will force the regex to match California only.

So, try [,/]([^,]*)[-/]. Here's a demo of how it works.

Upvotes: 0

Aran-Fey
Aran-Fey

Reputation: 43166

,\s*(\w\w)[^,]*-

will capture Ca in group 1.


,       comma
\s*     whitespace
(\w\w)  capture the first two characters
[^,]*   make sure there's no comma up to the next dash
-

Upvotes: 2

Related Questions