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
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.
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.
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.
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.
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+)/'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With