零零乙
2011-11-28 22:47
采纳率: 50%
浏览 202

正则表达式,以匹配包含新行的任何字符

Is there a regex to match "all characters including newlines"?

For example, in the regex below, there is no output from $2 because (.+?) doesn't include new lines when matching.

$string = "START Curabitur mollis, dolor ut rutrum consequat, arcu nisl ultrices diam, adipiscing aliquam ipsum metus id velit. Aenean vestibulum gravida felis, quis bibendum nisl euismod ut. 

Nunc at orci sed quam pharetra congue. Nulla a justo vitae diam eleifend dictum. Maecenas egestas ipsum elementum dui sollicitudin tempus. Donec bibendum cursus nisi, vitae convallis ante ornare a. Curabitur libero lorem, semper sit amet cursus at, cursus id purus. Cras varius metus eu diam vulputate vel elementum mauris tempor. 

Morbi tristique interdum libero, eu pulvinar elit fringilla vel. Curabitur fringilla bibendum urna, ullamcorper placerat quam fermentum id. Nunc aliquam, nunc sit amet bibendum lacinia, magna massa auctor enim, nec dictum sapien eros in arcu. 

Pellentesque viverra ullamcorper lectus, a facilisis ipsum tempus et. Nulla mi enim, interdum at imperdiet eget, bibendum nec END";

$string =~ /(START)(.+?)(END)/;

print $2;

转载于:https://stackoverflow.com/questions/8303488/regex-to-match-any-character-including-new-lines

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • ~Onlooker 2011-11-28 22:49
    已采纳

    Add the s modifier to your regex to cause . to match newlines:

    $string =~ /(START)(.+?)(END)/s;
    
    打赏 评论
  • 七度&光 2011-11-28 22:49

    You want to use "multiline".

    $string =~ /(START)(.+?)(END)/m;
    
    打赏 评论
  • 笑故挽风 2011-11-28 22:49

    Yeap, you just need to make . match newline :

    $string =~ /(START)(.+?)(END)/s;
    
    打赏 评论
  • 谁还没个明天 2011-11-28 22:53

    If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

    [\S\s]
    

    a character which is not a space or is a space… in other words, any character.

    You can also change modifiers locally in a small part of the regex, like so:

    (?s:.)
    
    打赏 评论