例如,这个正则表达式

(.*)<FooBar>

将匹配:

abcde<FooBar>

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

abcde
fghij<FooBar>

当前回答

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

其他回答

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

Use:

/(.*)<FooBar>/s

s使点(.)匹配回车符。

"."通常不匹配换行符。大多数正则表达式引擎允许您添加s标志(也称为DOTALL和SINGLELINE)来使“.”也匹配换行符。 如果失败了,你可以做一些类似[\S\ S]的事情。

试试这个:

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

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

我想在Java中匹配一个特定的if块:

   ...
   ...
   if(isTrue){
       doAction();

   }
...
...
}

如果我使用regExp

if \(isTrue(.|\n)*}

它包含方法块的右大括号,所以我使用

if \(!isTrue([^}.]|\n)*}

从通配符匹配中排除结束大括号。