Home > Back-end >  How do I match a string of the type S10101010 using a Perl regular expression?
How do I match a string of the type S10101010 using a Perl regular expression?

Time:10-15

I want to match a string of the type:

S10101010...

The script below matches/prints just "S10". How can I fix it?

$in = <STDIN>;

print $in=~/S(10) /;

CodePudding user response:

You can group, but do not capture, the 10 using (?:)

use warnings;
use strict;

my $in = 'abc S101010 def';
$in =~ /(S(?:10) )/;
print "$1\n";

The outer parens do the capturing into $1.

Prints:

S101010

Refer to perldoc perlre

CodePudding user response:

To check if it matches exactly, you want

/^S(?:10) \z/

^ means start of string.
\z means end of string.
(?:...) is used for grouping in regex. ((...) is a capture).

Don't forget to use chomp to clear the final line feed if you're reading from STDIN, or use $ instead of \z to allow a trailing line feed.


The match will be in $&.

if ( "S10101010" =~ /^S(?:10) \z/ ) {
   say $&;  # S10101010
}

You could also use a capture.

if ( my ($match) = "S10101010" =~ /^ ( S(?:10)  ) \z/x ) {
   say $match;  # S10101010
}

(Also used whitespace as allowed by /x.)

Of course, since you're matching the entire string, you could also just print the input, as the following full example does:

use 5.014;
use warnings;

defined( my $s = <> )
   or die("Premature EOF\n");

chomp($s);

if ( $s =~ /^S(?:10) \z/ ) {
   say $s;
} else {
   say "[no match]";
}
  • Related