Difference between regular expression modifiers (or flags) 'm' and 's'?

前端 未结 3 1230
余生分开走
余生分开走 2020-12-01 10:43

I often forget about the regular expression modifiers m and s and their differences. What is a good way to remember them?

As I understand t

3条回答
  •  鱼传尺愫
    2020-12-01 11:34

    I like the explanation in 'man perlre':

    m Treat string as multiple lines.
    s Treat string as single line.

    With multiple lines, ^ and $ apply to individual lines (i.e. just before and after newlines).
    With a single line, ^ and $ apply to the whole, and \n just becomes another character you can match.

    [Wrong]By using both m and s as you described, I would expect the second one to take precedence, so you would always be in multiline mode with /ism.[/Wrong]

    I didn't read far enough:
    The "/s" and "/m" modifiers both override the $* setting. That is, no matter what $* contains, "/s" without "/m" will force "^" to match only at the beginning of the string and "$" to match only at the end (or just before a newline at the end) of the string. Together, as /ms, they let the "." match any character whatsoever, while still allowing "^" and "$" to match, respectively, just after and just before newlines within the string.

提交回复
热议问题