Created
December 16, 2011 09:16
-
-
Save jihao/1485266 to your computer and use it in GitHub Desktop.
ruby string examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
irb(main):023:0> "".respond_to? "=~" | |
=> true | |
irb(main):024:0> "".respond_to? "match" | |
=> true | |
irb(main):030:0> Regexp.compile("").respond_to? "match" | |
=> true | |
irb(main):032:0> Regexp.compile("").respond_to? "=~" | |
=> true | |
正则表达式匹配 | |
irb(main):035:0> "http://www.haojii.com".match(/http:\/\/(www\.)?(\w*)(\.)?(com|net|cn)/) | |
=> #<MatchData "http://www.haojii.com" 1:"www." 2:"haojii" 3:"." 4:"com"> | |
字符串替换 | |
irb(main):039:0> "http://www.haojii.com".gsub("o","-") #gsub全部替换 | |
=> "http://www.ha-jii.c-m" | |
irb(main):043:0> "http://www.haojii.com".sub("o","-") #sub只替换第一个匹配到的 | |
=> "http://www.ha-jii.com" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment