May 11, 2012

Non Capturing Paranthesis (?:) in Regular Expressions

From my earlier blog on capturing, you might have understood about the capturing concept in regular expressions.

Let us now look the Non-capturing concept in regular expressions with a simple example

To achieve non-capturing parenthesis use "?:" 

E.g.  $input = +456.987c
        $input = ~/([-+]?[0-9]+(?:\.[0-9]*)?)([cf])$/     
   
     Where  $1 = ([-+]?[0-9]+(\.[0-9]*)?) #which matches '456.987'
                  $2 = ([cf])                                #which matches 'c'




Carefully observe, here
$2 is not (?:\.[0-9]*) but instead it is ([cf]), why because (?:\.[0-9]*) is starting with ?: which means it is not being captured, so $2 becomes ([cf])
                     
Advantages of Non-Capturing:
    1) Avoids unnecessary Capturing (Matches only what ever required)
    2) Efficiency Enhancement



Please refer to my earlier blog on capturing

I will be discussing about "Look Around" concepts of regular expressions in my coming blog.

Don't hesitate to comment if you have any doubts or queries on this topic.

Thanks for your valuable time and have a great day :-)


No comments:

Post a Comment