0

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.

4
  • By "alpha", do you mean uppercase ASCII letters? I.e., no such weird stuff as Ö or É? Commented Jun 13, 2013 at 10:18
  • This is a very elementary question. Did you search for an answer? What have you tried? What did you get as results? Commented Jun 13, 2013 at 10:19
  • 1
    @theTinMan If there's a duplicate question here on SO, feel free to mark this as such and redirect to the duplicate. I didn't find it, but it's not exactly easy to search for this thing.
    – Shpigford
    Commented Jun 13, 2013 at 10:21
  • It's easy to figure out reading the documentation. ruby-doc.org/core-2.0/Regexp.html Commented Jun 13, 2013 at 10:26

2 Answers 2

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

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

1
  • Thanks TIm, this is perfect!
    – Shpigford
    Commented Jun 13, 2013 at 10:24
2

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}-/] ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.