Ruby regex.scan

I use the Ruby scan () method to search for text in a specific format. Then I output it to a line separated by commas. The text I'm trying to find will look like this:

AB_ABCD_123456

Here is what I still found to find above. It works great:

text.scan(/.._...._[0-9][0-9][0-9][0-9][0-9][0-9]/)
puts text.uniq.sort.join(', ')

Now I need a regular expression that will find above with or without a two-letter country designation at the end. For example, I would like to find all three of the following:

AB_ABCD_123456
AB_ABCD_123456UK
AB_ABCD_123456DE

I know that I can use two or three different scans to achieve my result, but I wonder if there is a way to get all three with one regular expression.

+5
source share
4 answers
/.._...._[0-9][0-9][0-9][0-9][0-9][0-9](?:[A-Z][A-Z])?/

{}, :

/.{2}_.{4}_[0-9]{6}(?:[A-Z]{2})?/

: ? . () ( Ruby , ? ). ?: ( ( , ).

+12
 /.._...._\d{6}([A-Z]{2})?/
+1

split?

"AB_ABCD_123456".split(/_/).join(',')

, .

+1

:

text.scan(/\w{2}_\w{4}_\d{6}\w{0,2}/) 
#matches AB_ABCD_123456UK or ab_abcd_123456uk and so on...

text.scan(/[A-Z]{2}_[A-Z]{4}_\d{6}[A-Z]{0,2}/) 
# tighter, matches only AB_ABCD_123456UK and similars...
# and not something like ab_aBCd_123456UK or ab_abcd_123456uk and similars...

URL:

Ruby gsub/regex?

http://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#regexp

.

+1

All Articles