I'm playing around with Perl and trying to get a better understanding of its substring/regex functionality.
Say I have a string such as
[48:31.8] Sent: >33*1311875297587*eval*0*frame[0]*"A"<
and want to return 1311875297587. It will always be in that format. How would I do this using Perl?
Thanks
To search for a substring inside a string, you use index() and rindex() functions. The index() function searches for a substring inside a string from a specified position and returns the position of the first occurrence of the substring in the searched string.
Simple word matching In this statement, World is a regex and the // enclosing /World/ tells Perl to search a string for a match. 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 Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit. The \d is standardized to “digit”.
The '=~' operator is a binary binding operator that indicates the following operation will search or modify the scalar on the left. The default (unspecified) operator is 'm' for match. The matching operator has a pair of characters that designate where the regular expression begins and ends.
Assuming that "[48:31.8]..." is in $string, then:
my ($number) = $string =~ /\*(\d+)\*eval\*/;
$number
will be undefined if the string doesn't match, otherwise it will contain the digits between "*"
and "*eval*"
.
if ($str =~ /\*(\d+)\*/ ) {
print $1;
}
my ($num) = '>33*1311875297587*eval*0*frame[0]*"A"<' =~ /(\d{3,})/;
print $num;
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