class

Regexp

v1_8_7_330 - Show latest stable - Superclass: Object

Document-class: Regexp

A Regexp holds a regular expression, used to match a pattern against strings. Regexps are created using the /…/ and %r{…} literals, and by the Regexp::new constructor.

Constants

EXTENDED = INT2FIX(RE_OPTION_EXTENDED)

IGNORECASE = INT2FIX(RE_OPTION_IGNORECASE)

MULTILINE = INT2FIX(RE_OPTION_MULTILINE)

Files

  • lib/eregex.rb
  • lib/yaml/rubytypes.rb
  • re.c

3Notes

Cheat Sheet

svoop · Feb 10, 20093 thanks

I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE) as used by Ruby's Regexp class:

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/

Eagerness

svoop · Mar 8, 2010

Check out this simple example:

"Hello Ruby friend".sub(/^(.)e/, 'X') # => "Xnd" "Hello Ruby friend".sub(/^(.?)e/, 'X') # => "Xllo Ruby friend"

The question mark turns the dotstar into non-eager mode which means it will halt on the first subsequent "e" rather than the last one. This comes in handy e.g. for Cucumber step definitions.

Okay, but not really nice: /^I am using rvm "([^\"])" with gemset "(.)"$/

Much more readable and consistent equivalent to the above: /^I am using rvm "(.?)" with gemset "(.?)"$/

Loop through matches of your regular expression-based search

foliosus · Jun 21, 2011

If you want to loop through the matches of a regular expression, String#scan is your friend. You can do something like this:

matches = '12345'.scan(/\\d/)
matches.each do |m|
  puts m
end

# => 1
# => 2
# => 3
# => 4
# => 5