Ruby Programming/Reference/Objects/Regexp

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Class Regexp holds a regular expression, used to match a pattern of strings. Regular expressions can be created using /../ or by using the constructor "new".


[edit] CONSTANTS

  1. EXTENDED : Ignore spaces and newlines in regexp.
  2. IGNORECASE : Matches are case insensitive.
  3. MULTILINE : Newlines treated as any other character.

[edit] CLASS METHODS

  • compile : Regexp.compile( pattern [, options [ lang ] ] ) -> aRegexp
  •     This method is a synonym for method "new". 
    
  • escape : Regexp.escape( aString ) -> aNewString
  •    Escapes any characters that have special meaning in a regular expression. 
       For example : 
       Regexp.escape('\\*?{}.')  » \\\\\*\?\{\}\. 
    
  • last_match : Regexp.last_match -> aMatchData
  •     Returns the MatchData object generated by the last successful pattern match. 
        Equivalent to reading the global variable $~. 
    
  • new : Regexp.new( pattern [, options [ lang ] ] ) -> aRegexp
  •     Constructs a regular expression from the pattern. The pattern can be either a string or 
        a "regexp".
        For example: 
        Regexp.new("xyz") » /xyz/
    
  • quote : Regexp.quote( aString ) -> aNewString
  •     A synonym for escape method.
    

[edit] INSTANCE METHODS

  • == : rxp == aRegexp -> true or false
  •     Two regular expressions are equal if their patterns match and they have same character
        set code and theie casefold? values are same.
    
  • === : rxp === aString -> true or false
  •     Synonym for Regexp#=~ used in case statements
    
  • =~ : rxp === aString -> true or false
  •     Matches a regular expression with string and returns the offset of the start of match or nil
        if a match fails. 
    
  • ~ : ~ rxp -> anInteger or nil
  •     Match---Matches rxp against the contents of $_. Equivalent to rxp =~ $_. 
        For example:
        $_ = "input data"  
        ~ /at/  » 7  
    
  • casefold? : rxp.casefold? Returns true or false.
  •     Returns the value of case-insensitive flag.
    
  • kcode : rxp.kcode -> aString
  •     Returns character set code for the regexp.
    
  • match : rxp.match(aString) -> aMatchData or nil
  •     Returns a MatchData object or nil if match is not found.
    
  • source : rxp.source -> aString
  •     Returns the original string of the pattern.
        For example : /xyz/.source >> xyz