PHP regular expression to match lines starting with a special character

前端 未结 2 1277
猫巷女王i
猫巷女王i 2020-11-29 10:18

I have a text file with some configuration value. There a comment starts with a # I am trying to find a regular expression pattern that will find out all the lines that star

相关标签:
2条回答
  • 2020-11-29 10:45

    You forgot the multiline modifier (and you should not use the singleline modifier; also the case-insensitive modifier is unnecessary as well as the ungreedy modifier):

    preg_match_all("/^#(.*)$/m",$text,$m);
    

    Explanation:

    • /m allows the ^ and $ to match at the start/end of lines, not just the entire string (which you need here)
    • /s allows the dot to match newlines (which you don't want here)
    • /i turns on case-insensitive matching (which you don't need here)
    • /U turns on ungreedy matching (which doesn't make a difference here because of the anchors)

    A PHP code demo:

    $text = "1st line\n#test line this \nline #new line\naaaa #aaaa\nbbbbbbbbbbb#\ncccccccccccc\n#ffffdffffdffffd"; 
    preg_match_all("/^#(.*)$/m",$text,$m);
    print_r($m[0]);
    

    Results:

    [0] => #test line this 
    [1] => #ffffdffffdffffd
    
    0 讨论(0)
  • 2020-11-29 11:02

    You can simply write:

    preg_match_all('~^#.*~m', $text, $m);
    

    since the quantifier is greedy by default and the dot doesn't match newlines by default, you will obtain what you want.

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