re = /(?<!\d[ _-])(?<!\d)\d{4}(?:[_ -]?\d{4}){3}(?![_ -]?\d)/mx
str = '1234123412341234
(16 digits all together)
1234 1234 1234 1234
1234-1234-1234-1234
(card numbers with hyphens and spaces)
Find me 1234-1234-1234-1234 Find me (card numbers hidden amongst text)
What I\'m struggling to stop is the false positives I get, which I know are a direct result of achieving result number 4 above. The false positives being more than 16 digits which are clearly not card numbers. E.g
1) 1234-1234-1234-1234-1234'
# 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