re = /^((gir *0aa)|((((?![qvx])[a-z][a-hk-y]?[0-9][0-9]?)|(((?![qvx])[a-z][0-9][a-hjkstuw])|((?![qvx])[a-z][a-hk-y][0-9][abehmnprvwxy]))) *([0-9](?![cikmov])[a-z]{2}))|(((?![qvx])[a-z][a-hk-y]?[0-9][0-9]?)|((?![qvx])[a-z][0-9][a-hjkstuw])|((?![qvx])[a-z][a-hk-y][0-9][abehmnprvwxy])))$/im
str = 'GIR 0AA
W1 6LS
N1C 4UQ
N17 6LA
SW8 1UQ
CW3 9SS
SE5 0EG
WC2H 7LT
WC1N 2PL
HU12 0AR
N1C4UQ
N176LA
SW81UQ
CW39SS
SE50EG
WC2H7LT
WC1N2PL
HU120AR
W1
N1C
N17
SW8
CW3
SE5
WC2H
WC1N
HU12
QA12
AJ12
Q1A
A1V
QA1N
AZ1N
AB1Z'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Ruby, please visit: http://ruby-doc.org/core-2.2.0/Regexp.html