zoukankan      html  css  js  c++  java
  • ruby 正则表达式Regexp

    http://ruby-doc.org/core-2.1.2/Regexp.html

    Regexp

    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 theRegexp.new 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


    =~执行完如果匹配到了,返回第一个匹配位置的index索引值,0在ruby里为true,如果没有匹配到,返回nil,
    在ruby里,只有nil和false为false.其他的都为true
    测试一下:
    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"

    这时候可以写了

    app/helpers/packages_helper.rb

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

    _form.html.erb

    <%= image_tag youku_image_url(@package.app_icon), :width => 150 %>
  • 相关阅读:
    函数执行的预解释
    数组的基本知识点
    前端开发概述+JS基础细节知识点
    JS数据类型的转换规则
    call,apply,求最大最小值,平均数等基础编程知识
    JS面向对象程序设计(OOP:Object Oriented Programming)
    C++ 手记
    C++ 在堆中申请内存方法
    vc驿站视频教程笔记4 Cstring 讲解
    vc驿站视频教程笔记2 ansi 和 unicode
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/3786382.html
Copyright © 2011-2022 走看看