0

I have a simple program where the user can enter a string. After this the user can enter a regex. I need the string to be compared against this regex.

The following code do not work - the regex always fails.

And I know that its maybe because I am comparing a string with a string and not a string with a regex.

But how would you do this?

while(1){
    print "Enter a string: ";
    $input = <>;
    print "\nEnter a regex and see if it matches the string: ";
    $regex = <>;

    if($input =~ $regex){
        print "\nThe regex $regex matched the string $input\n\n";
    }
}

3 Answers 3

2
  1. Use lexical variables instead of global ones.

  2. You should remember that strings read by <> usually contain newlines, so it might be necessary to remove the newlines with chomp, like this:

    chomp(my $input = <STDIN>);
    chomp(my $regex = <STDIN>);
    
  3. You might want to interpret regex special characters taken from the user literally, so that ^ will match a literal circumflex, not the beginning of the string, for example. If so, use the \Q escape sequence:

    if ($input =~ /\Q$regex\E/) { ... }
    
  4. Don't forget to read the Perl FAQ in your journey through Perl. It might have all the answers before you even begin to specify the question: How do I match a regular expression that's in a variable?

Sign up to request clarification or add additional context in comments.

2 Comments

Thx for the fast reply :) But i still cant get this to work :(. The string wont match the regex.
Could you provide that string and regex?
1

You need to use a //, m//, or s/// — but you can specify a variable as the pattern.

if ($input =~ /$regex/) {
  print "match found\n";
}

3 Comments

@NikhilJain, I was talking about the syntax required in general: if you use =~ or !~ then you need to apply it to a matching type of operator.
yes, actually I thought the same thing that you are providing the options in general that's why I deleted my comment.
your solution works. As regex i entered /something_to_match/ where i just should type something_to_match without /.
0

I think you need to chomp input and regex variables. and correct the expression to match regex

chomp( $input );
chomp( $regex );
if($input =~ /$regex/){
    print "\nThe regex $regex matched the string $input\n\n";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.