Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a substring using Perl regex

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

like image 352
Roger Avatar asked Aug 01 '11 20:08

Roger


People also ask

How do I find a substring in a string in Perl?

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.

How do I match a string in regex in Perl?

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.

What is \d in Perl regex?

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”.

What is =~ in Perl?

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.


3 Answers

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*".

like image 148
Sean Avatar answered Sep 24 '22 08:09

Sean


if ($str =~ /\*(\d+)\*/ ) {
    print $1;
}
like image 20
Karoly Horvath Avatar answered Sep 23 '22 08:09

Karoly Horvath


my ($num) = '>33*1311875297587*eval*0*frame[0]*"A"<' =~ /(\d{3,})/;
print $num;
like image 37
abra Avatar answered Sep 24 '22 08:09

abra