How can I match a pipe character followed by whitespace and another pipe?

前端 未结 5 1515
春和景丽
春和景丽 2021-01-12 01:14

I am trying to find all matches in a string that begins with | |.

I have tried: if ($line =~ m/^\\\\\\|\\s\\\\\\|/) which didn\'t work. <

相关标签:
5条回答
  • 2021-01-12 01:38

    What about:

    m/^\|\s*\|/ 
    
    0 讨论(0)
  • 2021-01-12 01:46

    Pipe character should be escaped with a single backslash in a Perl regex. (Perl regexes are a bit different from POSIX regexes. If you're using this in, say, grep, things would be a bit different.) If you're specifically looking for a space between them, then use an unescaped space. They're perfectly acceptable in a Perl regex. Here's a brief test program:

    my @lines = <DATA>;
    
    for (@lines) {
        print if /^\| \|/;
    }
    
    __DATA__  
    | | Good - space  
    || Bad - no space  
    |   | Bad - tab  
     | | Bad - beginning space  
            Bad - no bars  
    
    0 讨论(0)
  • 2021-01-12 01:49

    You are escaping the pipe one time too many, effectively escaping the backslash instead.

    print "YES!" if ($line =~ m/^\|\s\|/);
    
    0 讨论(0)
  • 2021-01-12 01:49

    If it's a literal string you're searching for, you don't need a regular expression.

    my $search_for = '| |';
    my $search_in = whatever();
    if ( substr( $search_in, 0, length $search_for ) eq $search_for ) {
        print "found '$search_for' at start of string.\n";
    }
    

    Or it might be clearer to do this:

    my $search_for = '| |';
    my $search_in = whatever();
    if ( 0 == index( $search_in, $search_for ) ) {
        print "found '$search_for' at start of string.\n";
    }
    

    You might also want to look at quotemeta when you want to use a literal in a regexp.

    0 讨论(0)
  • 2021-01-12 01:52

    Remove the ^ and the double back-slashes. The ^ forces the string to be at the beginning of the string. Since you're looking for all matches in one string, that's probably not what you want.

    m/\|\s\|/
    
    0 讨论(0)
提交回复
热议问题