Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Regex - Print the matched value

Tags:

regex

perl

What is the perl regex to print the matched value? For eg I want to print 195 from this string

"2011-04-11 00:39:28,736::[main]::INFO (Main.java:73) Test.Main::main() Total Successful Transactions = 195". 

How can I do that? Thanks in advance

like image 678
CrazyCoder Avatar asked Apr 11 '11 05:04

CrazyCoder


People also ask

How do I print a matched pattern in Perl?

The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions. To print this matched pattern and the remaining string, m operator provides various operators which include $, which contains whatever the last grouping match matched.

What does =~ do in Perl?

The operator =~ associates the string with the regex match and produces a true value if the regex matched, or false if the regex did not match.

What is \b in Perl regex?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length. There are three different positions that qualify as word boundaries: Before the first character in the string, if the first character is a word character.

How do I match a variable in Perl?

Perl makes it easy for you to extract parts of the string that match by using parentheses () around any data in the regular expression. For each set of capturing parentheses, Perl populates the matches into the special variables $1 , $2 , $3 and so on. Perl populates those special only when the matches succeed.


1 Answers

You can use parentheses in regex to capture substrings. The captured groups are stored in $1, $2, and so on. Example:

while (<>) {     if (/Total Successful Transactions = (\d+)/) {         print "$1\n";     } } 

or, somewhat shorter:

while (<>) {     print "$1\n" if /Total Successful Transactions = (\d+)/; } 

You can also make use of the fact that the match operator (//) in list context returns a list of what was matched by groups:

$\ = '\n'; # Output newline after each print. while (<>) {     print for /Total Successful Transactions = (\d+)/; } 

Which lets you write a compact one-liner (the -l option automatically adds newlines to each print, among other things):

perl -lne 'print for /Total Successful Transactions = (\d+)/' 
like image 166
markusk Avatar answered Sep 25 '22 14:09

markusk