Blurman
Blurman

Reputation: 609

Perl match keyword until empty space

I have a variable containing string. I would like to get the string from after WARD= until the first empty space (in this example means yyy). I have limited knowledge in regex and pattern matching.

use strict;
use warnings;

my $var = "abc thisis long long stringggggg input=xxx WARD=yyy abcsdasdasd";
chomp($var);
my @ext = $var =~ /\b(WARD)\W+(\w+)/g;
print "@ext\n";

Upvotes: 0

Views: 278

Answers (2)

ikegami
ikegami

Reputation: 385657

my ($ward) = $str =~ /\bWARD=(\S*)/
   or die("Missing ward);

The \b prevents FORWARD=... from matching.

Upvotes: 1

Michał Turczyn
Michał Turczyn

Reputation: 37367

Try pattern:

(?<=WARD=)\S+

Explanation:

(?<=...) - positive lookbehind - assert what preceeds current position matches pattern inside (in place of ...)

WARD= - match WARD= literally

\S+ - match one or more of non-whitespace, so it will match as long as there is no whitespace.

Regex demo

EDIT

For sake of completeness, I will append @MarcoLuzzara suggestion, which is pattern WARD=(\S+)

Here logic changed a little, so let me explain new constructs:

(...) - capturing group, which matches pattern inside and stores it inside capturing group.

Another demo.

Upvotes: 0

Related Questions