例如,这个正则表达式

(.*)<FooBar>

将匹配:

abcde<FooBar>

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

abcde
fghij<FooBar>

当前回答

如果您正在使用Eclipse搜索,您可以启用“DOTALL”选项来生成'。'匹配任何字符,包括行分隔符:只需在搜索字符串的开头添加“(?s)”。例子:

(?s).*<FooBar>

其他回答

一般来说,。不匹配换行符,因此try ((.|\n)*)<foobar>。

通常,我们必须修改子字符串,在子字符串前面的行中散布一些关键字。考虑一个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")

而且替换后的机器和以前一样工作正常。

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

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

/YOUR_REGEXP/m

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

试题:* \ n *。*<FooBar>假设你也允许空换行。因为你允许任何字符在<FooBar>之前不包括任何字符。