Shpigford
Shpigford

Reputation: 25348

What would the regex be to detect this string?

I need to determine if a given string has the sequence dash-alpha-alpha-dash.

Example strings:

114888-ZV-209897
409-II-224858
86296-MO-184080
2459-ND-217906

What would be the the regex to determine that?

I'm using Ruby 1.9.3, FWIW.

Upvotes: 0

Views: 44

Answers (2)

the Tin Man
the Tin Man

Reputation: 160551

It's a simple pattern:

/-[A-Z]{2}-/

will do it.

Your regex is available at: http://rubular.com/r/6hn8BLc7rF

For instance:

"114888-ZV-209897"[/-[A-Z]{2}-/]
=> "-ZV-"

So use:

if  "114888-ZV-209897"[/-[A-Z]{2}-/] ...

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336178

if subject =~ /-[A-Z]{2}-/
    # Successful match
else
    # Match attempt failed
end

That [A-Z] thingy is a character class.

Upvotes: 2

Related Questions