Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Perl Reg exp: Parentheses in character class

Status
Not open for further replies.

shamino

Technical User
Jul 8, 2009
2
US
I am trying to match parentheses by puting the parentheses in a character class, but I cannot get it to work. Here is the sample code I am trying to run:

$line = 'hello(()())';

$line =~ /([\(\)]*)/;

print $1."\n";


I would think '(()())' will get printed, but it does not.

Any help/tips will be much appreciated.

Thanks.
 
I think your star is not being greedy enough? Try changing your "*" to a "+" and see if you get better results.
 
I got to my Unix box and tested it - I see what was happening. It was the fault of the star, I believe. The star says "match zero or more". The letter "h" in your string "hello" matches "zero or more" parenthesis, so $1 was '' - it matched the "h" but didn't capture anything. The plus sign will ensure you capture at least on parenthesis.
 
Try something like this to see what I was talking about:

Code:
$line = 'hello(()())';
@captures = $line =~ /([\(\)]*)/g; #added the "g" flag for global
print "$_\n" foreach (@captures);
 
BTW, there's no need to escape parenthesis characters within a character class. This is fine:
Code:
$line =~ /([()]+)/;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top