Ruby學習筆記-正則表達式 Posted on 2011-11-29 17:55 Glen He 閱讀(4998) 評論(0) 編輯 收藏 1.建立正則表達式 a) reg1 = /^[a-z]*$/ #將模式的定義放在兩個正斜槓之間,返回一個Regexp對象 b) reg2 = Regexp.new(‘^[a-z]*$’) #建立一個Regexp對象 c) reg3 = %r{^[a-z]*$} #使用前置的%r 2.匹配正則式: String和Regexp都支持如下兩個方法 a) match方法: 匹配成功時返回MatchData類的一個實例;不然返回nil; b) =~ 操做符: 匹配成功,返回一個索引(integer);不然,返回nil; 例: puts( /abc/ =~ 'abc' ) #=>return 0 puts( /abc/ =~ 'cdg' ) #=>return nil puts( /abc/.match('abc') ) #=>return abc puts( /abc/.match('cdg') ) #=>return nil 3.匹配組 在Ruby正則表達式中,能夠用正則式匹配一個或多個子字符串;方法是將正 則式用小括號括起來;使用小括號指定的獲取子字符串,能夠將匹配的字符串保存;以下正則式中有兩個組(hi)和(h…o): /(hi).*(h...o)/ =~ "The word 'hi' is short for 'hello'." 匹配成功時, 會把匹配的值賦給一些變量(正則式中有多少組就有多少變量), 這些變量能夠經過$1,$2,$3…的形式訪問;若是執行上面的那行代碼,可使用$1,$2來訪問變量: print ( $1, " ", $2, "\n" ) #=> hi hello Note: 若是整個正則式匹配不成功,那麼就不會就有變量被初始化, 而是返回nil. 4. MatchData類型 前面也提到過了,使用=~時返回的是一個整數或nil, 面使用match方法時會返回MatchData對象, 它包含了匹配模式的結果;乍一看,很像是字符串: puts( /cde/.match('abcdefg') ) #=> cde #=>cde puts( /cde/=~('abcdefg') ) #=> cde #=>2 實際上, 它是MatchData類的一個實例且包含一個字符串: p( /cde/.match('abcdefg') ) #=> #<MatchData: 「cde」 > 可使用MatchData對象的to_a或captures方法返回包含其值的一個數組: x = /(^.*)(#)(.*)/.match( 'def myMethod # This is a very nice method' ) x.captures.each{ |item| puts( item ) } 上面代碼會輸出: def myMethod # This is a very nice method Note: captures 和to_a方法有一點點區別,後者會包含原始串 x.captures #=>["def myMethod ","#"," This is a very nice method"] x.to_a #=>["def myMethod # This is a very nice method","def myMethod ","#"," This is a very nice method"] 5. Pre & Post 方法 a) pre_match或($`): 返回匹配串前的串 b) post_match或($'): 返回匹配串後的串 x = /#/.match( 'def myMethod # This is a very nice method' ) puts( x.pre_match ) #=> def myMethod puts( x.post_match ) #=> This is a very nice method 6. 貪婪匹配 當一個字符串包含多個可能的匹配時,有時可能只想返回第一個匹配的串; 有時可能想返回全部匹配的串,這種狀況就叫貪婪匹配;符號*(0 or more) 和 + (1 or more)能夠用來進行貪婪匹配。使用符號? (0 or 1) 進行最少匹配; puts( /.*at/.match('The cat sat on the mat!') ) #=> returns: The cat sat on the mat puts( /.*?at/.match('The cat sat on the mat!') ) #=> returns: The cat 7. 字符串中的方法 a) =~ 和match: 用法同Regexp. b) String.scan(pattern):儘量多的去匹配,並把第一個匹配添加到數組中. TESTSTR = "abc is not cba" b = /[abc]/.match( TESTSTR ) #=> MatchData: "a" puts( "--scan--" ) a = TESTSTR.scan(/[abc]/) #=> Array: ["a", "b", "c", "c", "b", "a"] 此外,還能夠給sacn方法傳遞一個block: a = TESTSTR.scan(/[abc]/){|c| print( c.upcase ) } #=> ABCCBA 「fjkdlasjfldjffjladsjflka;jd".scan(/(f)(j)k/){|t| puts "#{t}>>>>>>>>>>>>>"} ["f", "j"]>>>>>>>>> 若是正則當中有括號,t表明的是由匹配到括號中的模式的值組成的數組, 若是沒有括號,t表明匹配整個模式的值 c) String.split(pattern):基於pattern來分割原串並返回一個數組;若是pattern爲空(//),就把原串分割爲字符; s = "def myMethod # a comment" p( s.split( /m.*d/ ) ) # => ["def ", " # a comment"] p( s.split( /\s/ ) ) #=> ["def", "myMethod", "#", "a", "comment"] p( s.split( // ) ) # => ["d", "e", "f", " ", "m", "y", "M", "e", "t", "h", "o", "d", " ", "#", " ", "a", " ", "c", "o", "m", "m", "e", "n", "t"] d) String. slice(pattern):返回匹配的串(原串不變), String. Slice!(pattern):返回匹配的串並在原串刪除匹配的串(修改了原串的值) s = "def myMethod # a comment " puts( s.slice( /m.*d/ ) ) #=> myMethod puts( s ) #=> def myMethod # a comment puts( s.slice!( /m.*d/ ) ) #=> myMethod puts( s ) #=> def # a comment 8.正則表達式匹配規則 規則 說明 /a/ 匹配字符a /\?/ 匹配特殊字符?。特殊字符包括^, $, ? , ., /, \, [, ], {, }, (, ), +, *. . 匹配任意字符,例如/a./匹配ab和ac。 /[ab]c/ 匹配ac和bc,[]之間表明範圍,例如:/[a-z]/ , /[a-zA-Z0-9]/。 /[^a-zA-Z0-9]/ 匹配不在該範圍內的字符串 /[\d]/ 表明任意數字 /[\w]/ 表明任意字母,數字或者_ /[\s]/ 表明空白字符,包括空格,TAB和換行 /[\D]/,/[\W]/,/[\S]/ 均爲上述的否認狀況 ? 表明0或1個字符 * 表明0或多個字符 + 表明1或多個字符 /d{3}/ 匹配3個數字 /d{1,10}/ 匹配1-10個數字 d{3,}/ 匹配3個數字以上 /([A-Z]\d){5}/ 匹配首位是大寫字母,後面4個是數字的字符串 . 匹配不到 \n 單獨的一個反斜槓不能做爲任何合法的字符 轉義字符計算字符串長度時只能計做一個字符 字符串「abc\0xyz」:其中有一個轉義字符'\0',它是字符串結束符,因此,當用函數strlen來測試該字符串的長度時,結果應該爲4(而不是8)。 str= "<p>一個反斜槓不能做爲\n</p>" str.scan(/<p>.*?\n<\/p>/) 返回[] 由於其中有\n .沒法匹配 只要字符串當中出現了\n 實用.去匹配就返回nil
我的微信:hellocongzhi,驗證信息:博客園同窗,歡迎隨時交流溝通技術心得正則表達式