Skip to content

Instantly share code, notes, and snippets.

@ejhayes
Created June 13, 2013 18:14
Show Gist options
  • Save ejhayes/5776005 to your computer and use it in GitHub Desktop.
Save ejhayes/5776005 to your computer and use it in GitHub Desktop.
Regex with optional groups. Useful for pulling out information about what you are looking for and where you are looking for it. For example: police records near sacramento, ca
# Uses this regex: ^((?:(?!(?:near|in)).)*)(?:(?:near|in)\s*(.*))?$
irb(main):001:0> /^((?:(?!(?:near|in)).)*)(?:(?:near|in)\s*(.*))?$/.match('police records near sacramento, ca')
=> #<MatchData "police records near sacramento, ca" 1:"police records " 2:"sacramento, ca">
irb(main):002:0> r=/^((?:(?!(?:near|in)).)*)(?:(?:near|in)\s*(.*))?$/.match('police records near sacramento, ca')
=> #<MatchData "police records near sacramento, ca" 1:"police records " 2:"sacramento, ca">
irb(main):003:0> r[0]
=> "police records near sacramento, ca"
irb(main):004:0> r[1]
=> "police records "
irb(main):005:0> r[2]
=> "sacramento, ca"
irb(main):006:0>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment