Reputation: 10695
I have example inputs to a program. They are
"1866TL",
and "965937","
.
The comma is part of what I am trying to match.
I want to match if there are alpha characters in the inputs.
I am getting the argument from @ARGV.
$input_line = $ARGV[0];
if ($input_line =~ m/\A\"\d+\D+\d*\",/)
{
print "Bad match\n";
}
else
{
print "Good match\n";
}
If I substitute .
for \"
, I get what I expect, Bad Match
for the first example that contains TL
, but not if I put literal quotes \"
in the regular expression.
How do I represent this input properly as a regex?
Am I missing how =~
works? I am expecting the first value "1866TL",
to match and for the program to print out Bad Match
.
Interestingly, if I print out $input_line
, figure the quotes have been stripped and search this way, I get what I expect.
$input_line = $ARGV[0];
print $input_line."\n";
if ($input_line =~ m/\A\d+[^0-9]+\d*/)
{
print "Bad match\n";
}
else
{
print "Good match\n";
}
So, what is happening? Are quotes stripped by Perl? Am I missing something else?
Upvotes: 1
Views: 131
Reputation: 386386
So, what is happening? Are quotes stripped by Perl? Am I missing something else?
In Perl, the string literal "abc"
(a piece of code) produces the string abc
(a value). If you want to create the string "abc"
, you need to use '"abc"'
, "\"abc\""
or similar.
Something similar is happening in your shell. For example, in sh
and derivatives, foo "abc"
pass the string abc
to program foo
. If you want to pass "abc"
, you need to use foo '"abc"'
or foo \"abc\"
or similar.
Upvotes: 2
Reputation: 241998
The problem of your regex might be that \D
matches too much, i.e. it can match double quotes and commas as well. To prevent that, use a more specific class:
m/\A"\d+[^0-9",]+\d*",/
as already adviced in https://stackoverflow.com/a/17552454/1030675.
Upvotes: 0
Reputation: 240364
Your code as written works just fine for me. Although there's actually no need to backslash the quotes.
Upvotes: 1