æ£è¦è¡¨ç¾ã®ã¾ã¨ã
åããããããã¼ã¸ããªãã£ãã®ã§ã¡ã¢ã£ã¨ãã
åºæ¬
"æåå" =~ /æ£è¦è¡¨ç¾/
åºæ¬ã¯ããã ãã§ããããããã°ç¹æ®å¤æ°ã«çµæãã»ãããããããªããã°nilãè¿ãã
- $` ãããããç®æã®å
- $& ãããããç®æ
- $' ãããããç®æã®å¾
"Hello Regular Expression." =~ /Regular/ print "#{$`}<<#{$&}>>#{$'}" # Hello <<Regular>> Expression.
Perlã©ã¤ã¯ã«$1ã9ã§ãã°ã«ã¼ãåããç®æãåå¾ã§ããã
"Hello <b>Regular</b> Expression." =~ /<b>(.*?)<\/b>/ print $1 # Regular
(.*?)ã¨ãã¦ããã®ã¯ããã©ã«ãã§ã§ããã ãé·ãæååã¨ããããããã¨ããããã§ãæå®ããªãã¨åãã¿ã°ãè¤æ°ããå ´åã«æã£ãçµæã«ãªããªãã£ãã
"Hello <b>Regular</b> <b>Expression</b>." =~ /<b>(.*)<\/b>/ print $1 # Regular</b> <b>Expression
æ½åº
String#scanã§ãããããç®æãå ¨ã¦æ½åºã§ããã便å©ï¼
p "Hello <b>Regular</b> <b>Expression</b>.".scan(/<b>(.*?)<\/b>/) # [["Regular"],["Expression"]]
ç½®æ
String#gsubã§ãããããç®æãå
¨ã¦ç½®æã
String#subã¯æåã«ãããããç®æã®ã¿ç½®æ
p "Hello <b>Regular</b> <b>Expression</b>.".gsub(/(<.*?>)/, '') # Hello Regular Expression.
æ£è¦è¡¨ç¾ã¯ã©ã¹
æ£è¦è¡¨ç¾ãªãã©ã«ã¯Regexpãããããã¼ã¿ã¯MatchDataã¯ã©ã¹ã¤ã³ã¹ã¿ã³ã¹ã«æ ¼ç´ããã¦ããã®ã§ãä¸è¨ã®ããã«æ¤ç´¢ãããã¨ãåºæ¥ãã
str = "Hello <b>Regular</b> Expression." data = /<b>(.*?)<\/b>/.match(str) p data[0] # $& ã¨ç価 p data[1] # $1 ã¨ç価 p data.pre_match # $` ã¨ç価 p data.post_match # $' ã¨ç価 p data.offset(0) # ãããç®æã®ã¤ã³ããã¯ã¹ [éå§, çµäº+1] p data.length # ãããããæ° # "<b>Regular</b>" # "Regular" # "Hello " # " Expression." # [6, 20] # 2
ç¹å®ãµã¤ããããªã³ã¯ãæ½åº
試ãã«ãªã³ã¯ã ãæ½åºãã¦ã¿ããç¹å®ãã¡ã¤ã«ï¼æ¡å¼µåï¼ã ããã¦ã³ãã¼ãã¾ã§ãããã£ããã©éä¸ã§åå°½ããã®ã§ä»åã¯ããã¾ã§ãã
require 'open-uri' str = "" open("http://www.google.co.jp") do |r| r.each do |l| str += l end end reg = /href=['"](.*?)['"]/ str.scan(reg).each do |item| puts item end