Diemauerdk
Diemauerdk

Reputation: 5948

How to use an user input as a regex?

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";
    }
}

Upvotes: 0

Views: 2784

Answers (3)

raina77ow
raina77ow

Reputation: 106453

  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?

Upvotes: 2

skywalker
skywalker

Reputation: 23

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";
}

Upvotes: 0

geekosaur
geekosaur

Reputation: 61449

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

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

Upvotes: 1

Related Questions