Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract string between two dots

Tags:

regex

perl

I have a string of the following format:

word1.word2.word3

What are the ways to extract word2 from that string in perl? I tried the following expression but it assigns 1 to sub:

@perleval $vars{sub} = $vars{string} =~ /.(.*)./; 0@

EDIT:

I have tried several suggestions, but still get the value of 1. I suspect that the entire expression above has a problem in addition to parsing. However, when I do simple assignment, I get the correct result:

@perleval $vars{sub} = $vars{string} ; 0@

assigns word1.word2.word3 to variable sub

like image 853
Nazar Avatar asked Jan 30 '23 00:01

Nazar


1 Answers

  • . has a special meaning in regular expressions, so it needs to be escaped.
  • .* could match more than intended. [^.]* is safer.
  • The match operator (//) simply returns true/false in scalar context.

You can use any of the following:

$vars{sub} = $vars{string} =~ /\.([^.]*)\./ ? $1 : undef;

$vars{sub} = ( $vars{string} =~ /\.([^.]*)\./ )[0];

( $vars{sub} ) = $vars{string} =~ /\.([^.]*)\./;

The first one allows you to provide a default if there's no match.

like image 102
ikegami Avatar answered Feb 01 '23 14:02

ikegami