正则 多行匹配

Posted by wxianfeng Mon, 15 Nov 2010 21:41:00 GMT

多行匹配也很常见,例如截取html源码的时候很有用,实现多行匹配只需要在正则后面加m即可 例如

/http:(.*?)\s?/m

ruby demo:

1

p "ab\r\n334cd".match(/ab(.*)cd/) # nil

p "ab\r\n334cd".match(/ab(.*)cd/m) # #<MatchData "ab\r\n334cd" 1:"\r\n334">

2,

str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><pre>\n<code class=\"ruby\">\nputs \"hello world\"\nputs \"hello world\"\n</code>\n</pre></body></html>\n"

p str.match(/<body>(.*)<\/body>/m)[0] # "<body><pre>\n<code class=\"ruby\">\nputs \"hello world\"\nputs \"hello world\"\n</code>\n</pre></body>"

p str.match(/<body>(.*)<\/body>/)[0] # nil

This entry was posted on Mon, 15 Nov 2010 21:41:00 GMT and Posted in . You can follow any any response to this entry through the Atom feed. You can leave a comment or a trackback from your own site.

Tags ,


Trackbacks

Use the following link to trackback from your own site:
http://blog.wxianfeng.com/trackbacks?article_id=95

Comments

Leave a comment