ruby 正则表达式Regexp

作者: angela_
发布时间:2015-07-13 11:29:38


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.

Regular expressions (regexps) are patterns which describe the contents of a string. They’re used for testing whether a string contains a given pattern, or extracting the portions that match. They are created with the /pat/ and %r{pat} literals or constructor.

A regexp is usually delimited with forward slashes (/). For example:

/hay/ =~ 'haystack'   #=> 0  /y/.match('haystack') #=> #<MatchData "y">
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and Stringso the order of String and Regexp do not matter. Other classes may have different implementations of =~.) If a match is found, the operator returns index of first match in string, otherwise it returns nil.
/hay/ =~ 'haystack'   #=> 0  'haystack' =~ /hay/   #=> 0  /a/   =~ 'haystack'   #=> 1  /u/   =~ 'haystack'   #=> nil
/ay/ =~'hay' #=> 1


irb(main):011:0> /hay/ =~ 'hayaaa'  => 0  irb(main):012:0> /hayaaaaa/ =~ 'hayaaa'  => nil  irb(main):013:0> /t/ =~ 'hayaaa'  => nil  irb(main):014:0> p 'tesdt' if 0  "tesdt"  => "tesdt"



def youku_image_url(url)    /http:\/\// =~ url ? url : "http://r#{rand(4) + 1}{url}"  end


<%= image_tag youku_image_url(@package.app_icon), :width => 150 %>