How can I convert a string into a regular expression that matches itself in Perl?

前端 未结 5 1212
轮回少年
轮回少年 2021-01-13 20:43

How can I convert a string to a regular expression that matches itself in Perl?

I have a set of strings like these:

Enter your selection:
Enter Code          


        
相关标签:
5条回答
  • 2021-01-13 20:53

    Why use a regular expression at all? Since you aren't doing any capturing and it seems you will not be going to allow for any variations, why not simply use the index builtin?

    $s1 = 'hello, (world)?!';
    $s2 = 'he said "hello, (world)?!" and nothing else.';
    
    if ( -1 != index  $s2, $s1 ) {
        print "we've got a match\n";
    }
    else {
        print "sorry, no match.\n";
    }
    
    0 讨论(0)
  • 2021-01-13 20:59

    As Brad Gilbert commented use quotemeta:

    my $regex = qr/^\Q$string\E$/;
    

    or

    my $quoted = quotemeta $string;
    my $regex2 = qr/^$quoted$/;
    
    0 讨论(0)
  • 2021-01-13 21:02

    To put Brad Gilbert's suggestion into an answer instead of a comment, you can use quotemeta function. All credit to him

    0 讨论(0)
  • 2021-01-13 21:03

    From http://www.regular-expressions.info/characters.html :

    there are 11 characters with special meanings: the opening square bracket [, the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening round bracket ( and the closing round bracket )

    In Perl (and PHP) there is a special function quotemeta that will escape all these for you.

    0 讨论(0)
  • 2021-01-13 21:05

    There is a function for that quotemeta.

    quotemeta EXPR
    Returns the value of EXPR with all non-"word" characters backslashed. (That is, all characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings.

    If EXPR is omitted, uses $_.

    0 讨论(0)
提交回复
热议问题