例如,这个正则表达式
(.*)<FooBar>
将匹配:
abcde<FooBar>
但我如何让它在多行之间匹配呢?
abcde
fghij<FooBar>
例如,这个正则表达式
(.*)<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
其他回答
请注意,(.|\n)*的效率可能低于(例如)[\s\ s]*(如果您的语言的正则表达式支持这种转译),也低于查找如何指定制造的修饰符。还要匹配换行符。或者你也可以使用POSIXy选项,比如[[:space:][:^space:]]*。
我想在Java中匹配一个特定的if块:
...
...
if(isTrue){
doAction();
}
...
...
}
如果我使用regExp
if \(isTrue(.|\n)*}
它包含方法块的右大括号,所以我使用
if \(!isTrue([^}.]|\n)*}
从通配符匹配中排除结束大括号。
选项1
一种方法是使用s标志(就像接受的答案一样):
/(.*)<FooBar>/s
演示1
选项2
第二种方法是使用m (multiline)标志和以下任何模式:
/([\s\S]*)<FooBar>/m
or
/([\d\D]*)<FooBar>/m
or
/([\w\W]*)<FooBar>/m
演示2
RegEx电路
jex。Im可视化正则表达式:
Use:
/(.*)<FooBar>/s
s使点(.)匹配回车符。
通常,我们必须修改子字符串,在子字符串前面的行中散布一些关键字。考虑一个XML元素:
<TASK>
<UID>21</UID>
<Name>Architectural design</Name>
<PercentComplete>81</PercentComplete>
</TASK>
假设我们想将81修改为其他值,比如40。首先识别。UID.21…,然后跳过包括\n在内的所有字符,直到。percentcompleted ..正则表达式模式和replace规范是:
String hw = new String("<TASK>\n <UID>21</UID>\n <Name>Architectural design</Name>\n <PercentComplete>81</PercentComplete>\n</TASK>");
String pattern = new String ("(<UID>21</UID>)((.|\n)*?)(<PercentComplete>)(\\d+)(</PercentComplete>)");
String replaceSpec = new String ("$1$2$440$6");
// Note that the group (<PercentComplete>) is $4 and the group ((.|\n)*?) is $2.
String iw = hw.replaceFirst(pattern, replaceSpec);
System.out.println(iw);
<TASK>
<UID>21</UID>
<Name>Architectural design</Name>
<PercentComplete>40</PercentComplete>
</TASK>
子组(.|\n)可能是缺失的组$3。如果我们通过(?:.|\n)使它不捕获,那么$3是(<PercentComplete>)。因此,pattern和replaceSpec也可以是:
pattern = new String("(<UID>21</UID>)((?:.|\n)*?)(<PercentComplete>)(\\d+)(</PercentComplete>)");
replaceSpec = new String("$1$2$340$5")
而且替换后的机器和以前一样工作正常。