I have a text file which is like following.
Jack Boy
Jill Girl
Jam ????
John Boy
Michelle Girl
I have written this, which I intended to match only lines that contain two words and not the line Jam ????
. It is not working.
if ( $line =~ ( /(\w+)\s+(\w+)/ ) && !( m/\?\?\?\?/ ) )
If you are also processing the data then a regular expression is the wrong tool for this.
You should simply split each line into fields and check whether the second field contains nothing but question marks.
Like this
use strict;
use warnings;
while (my $line = <DATA>) {
my @fields = split ' ', $line;
next unless $fields[1] =~ /[^?]/;
print $line;
}
__DATA__
Jack Boy
Jill Girl
Jam ????
John Boy
Michelle Girl
output
Jack Boy
Jill Girl
John Boy
Michelle Girl
Are these the only two options: two words or a word and ????
?
If so, the first part /(\\w)+\\s+(\\w+)/
is enough.
\\w
doesn't match ?
.
I see no need to match metacharacters for your specific input:
use warnings;
use strict;
while (<DATA>) {
print if /(\w+)\s+(\w+)/;
}
__DATA__
Jack Boy
Jill Girl
Jam ????
John Boy
Michelle Girl
Previous answers have covered that this isn't really the right process, but sometimes filtering strings by regular expression is helpful in a single if statement.
You almost had it! It's missing the matching operator in the second half of the if statement.
if ($line =~ (/(\\w+)\\s+(\\w+)/) && !($line =~ m/\\?\\?\\?\\?/))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.