正则 ?: 非捕获组

Posted by wxianfeng Wed, 21 Mar 2012 03:03:00 GMT

今天一个同事 问我 正则 里 ?: 什么意思,记得 以前知道的 , 愣是 忘记了 ,查了下 是非捕获组的意思!

捕获组
()内的是分组,可以用 $1,$2…取值, 被存在了内存中, 留反向引用.
demo:

ruby-1.9.2-p290 :022 >   "abcabc".match(/(abc)/)
 => #<MatchData "abc" 1:"abc"> 
ruby-1.9.2-p290 :023 > $1
 => "abc" 

非捕获组
(?:) 内的不当作分组, 分组内内容,内存中没有.
demo:

ruby-1.9.2-p290 :024 > "abcabc".match(/(?:abc)/)
 => #<MatchData "abc"> 
ruby-1.9.2-p290 :025 > $1
 => nil 

那么这个有什么用呢, 可以节省内存

demo

ruby-1.9.2-p290 :033 > "hello" =~ /h(i|ello)/
 => 0 
ruby-1.9.2-p290 :033 > $1
 => "ello" 
ruby-1.9.2-p290 :034 > "hello" =~ /h(?:i|ello)/
 => 0 
ruby-1.9.2-p290 :035 > $1
=> nil

This entry was posted on Wed, 21 Mar 2012 03:03: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://wxianfeng.com/trackbacks?article_id=230

  1. league of angels hack Tool Download league of angels hack Tool Download
    正则 ?: 非捕获组 | 0x64

Comments

  1. Avatar
    Rock {{count}} days ago:

    很喜欢你的blog,很实用,多写写啊

Leave a comment