例如,这个正则表达式

(.*)<FooBar>

将匹配:

abcde<FooBar>

但我如何让它在多行之间匹配呢?

abcde
fghij<FooBar>

当前回答

这取决于语言,但应该有一个可以添加到正则表达式模式的修饰符。在PHP中是:

/(.*)<FooBar>/s

结尾的s使点匹配所有字符,包括换行符。

其他回答

使用RegexOptions.Singleline。它改变了…的意思。要包含换行符。

Regex.Replace(content, searchText, replaceText, RegexOptions.Singleline);

通常在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

在Ruby中,你可以使用'm'选项(多行):

/YOUR_REGEXP/m

有关更多信息,请参阅ruby-doc.org上的Regexp文档。

试试这个:

((.|\n)*)<FooBar>

它基本上是说“任何字符或换行符”重复0次或多次。

这取决于语言,但应该有一个可以添加到正则表达式模式的修饰符。在PHP中是:

/(.*)<FooBar>/s

结尾的s使点匹配所有字符,包括换行符。