正则 ?: 非捕获组

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,很实用,多写写啊

  2. Avatar
    Reginald over {{count}} years ago:

    The SEER is determined by the cooling output during
    the winter divided by its electric input during the winter.

    Heat pumps are used for cooling about seven months a year while conventional systems are typically used five months a year.

  3. Avatar
    Reginald over {{count}} years ago:

    The SEER is determined by the cooling output during the winter divided by its electric input during the winter.
    Heat pumps are used for cooling about seven months a year while conventional systems are typically used five months
    a year.

  4. Avatar
    Passenger ships Ancona Patras over {{count}} years ago:

    You really make it seem so easy with your presentation but
    I find this topic to be really something which I think
    I wouuld never understand. It seems too complicated and very broad for me.

    I’m lookinmg forward for your next post, I’ll tryy to get the hang of it!

  5. Avatar
    Passenger ships Ancona Patras over {{count}} years ago:

    You redally make it seem so easy with your presentation but I
    find thuis topic too be really something which I think I would never understand.
    It srems too complicated and very broad for me. I’m looking forward for your
    next post, I’ll try to get the hanng of it!

Leave a comment