例如,这个正则表达式
(.*)<FooBar>
将匹配:
abcde<FooBar>
但我如何让它在多行之间匹配呢?
abcde
fghij<FooBar>
例如,这个正则表达式
(.*)<FooBar>
将匹配:
abcde<FooBar>
但我如何让它在多行之间匹配呢?
abcde
fghij<FooBar>
当前回答
解决方案:
使用模式修饰符sU将在PHP中获得所需的匹配。
例子:
preg_match('/(.*)/sU', $content, $match);
来源:
模式修饰符
其他回答
这对我来说是最简单的方法:
(\X*)<FooBar>
Use:
/(.*)<FooBar>/s
s使点(.)匹配回车符。
通常在PowerShell中搜索三个连续的行,它看起来像这样:
$file = Get-Content file.txt -raw
$pattern = 'lineone\r\nlinetwo\r\nlinethree\r\n' # "Windows" text
$pattern = 'lineone\nlinetwo\nlinethree\n' # "Unix" text
$pattern = 'lineone\r?\nlinetwo\r?\nlinethree\r?\n' # Both
$file -match $pattern
# output
True
奇怪的是,这将是Unix文本在提示符,但Windows文本在文件中:
$pattern = 'lineone
linetwo
linethree
'
下面是打印行结束符的方法:
'lineone
linetwo
linethree
' -replace "`r",'\r' -replace "`n",'\n'
# Output
lineone\nlinetwo\nlinethree\n
一般来说,。不匹配换行符,因此try ((.|\n)*)<foobar>。
请注意,(.|\n)*的效率可能低于(例如)[\s\ s]*(如果您的语言的正则表达式支持这种转译),也低于查找如何指定制造的修饰符。还要匹配换行符。或者你也可以使用POSIXy选项,比如[[:space:][:^space:]]*。