我基本上是在尝试替换一篇大文本中的所有脚注。我在Objective-C中这样做的原因有很多,所以请假设这一限制。
每一个脚注都是这样的:[脚注
每个脚注都以此结尾:]
这两个标记之间绝对可以有任何东西,包括换行符。然而,它们之间永远不会有]。
因此,本质上我想匹配Footnote,然后匹配除,until ]之外的任何内容。
这是我所能识别的最接近所有脚注的地方:
NSString *regexString = @"[\\[][F][o][o][t][n][o][t][e][^\\]\n]*[\\]]";使用这个正则表达式可以识别780/889脚注。而且,这780似乎都不是假警报。它似乎唯一遗漏的是那些带换行符的脚注。
我在www.regular-expressions.info上花了很长时间,特别是在关于点的页面(http://www.regular-expressions.info/dot.html)上。这帮助我创建了上面的正则表达式,但我还没有真正弄清楚如何包含任何字符或换行符,除了右括号。
相反,使用以下正则表达式可以捕获所有脚注,但它捕获的文本太多,因为*太贪婪:(?s)[\\[][F][o][o][t][n][o][t][e].*[\\]]
下面是一些运行正则表达式的示例文本:
<p id="id00082">[Footnote 1: In the history of Florence in the early part of the XVIth century <i>Piero di Braccio Martelli</i> is frequently mentioned as <i>Commissario della Signoria</i>. He was famous for his learning and at his death left four books on Mathematics ready for the press; comp. LITTA, <i>Famiglie celebri Italiane</i>, <i>Famiglia Martelli di Firenze</i>.—In the Official Catalogue of MSS. in the Brit. Mus., New Series Vol. I., where this passage is printed, <i>Barto</i> has been wrongly given for Braccio.</p>
<p id="id00083">2. <i>addi 22 di marzo 1508</i>. The Christian era was computed in Florence at that time from the Incarnation (Lady day, March 25th). Hence this should be 1509 by our reckoning.</p>
<p id="id00084">3. <i>racolto tratto di molte carte le quali io ho qui copiate</i>. We must suppose that Leonardo means that he has copied out his own MSS. and not those of others. The first thirteen leaves of the MS. in the Brit. Mus. are a fair copy of some notes on physics.]</p>
<p id="id00085">Suggestions for the arrangement of MSS treating of particular subjects.(5-8).</p>
When you put together the science of the motions of water, remember to include under each proposition its application and use, in order that this science may not be useless.--
[Footnote 2: A comparatively small portion of Leonardo's notes on water-power was published at Bologna in 1828, under the title: "_Del moto e misura dell'Acqua, di L. da Vinci_".]在本例中,有两个脚注和一些非脚注文本。正如您所看到的,第一个脚注中包含两个换行符。第二个不包含换行符。
我上面提到的第一个正则表达式将设法捕获此示例文本中的Footnote 2,但它不会捕获Footnote 1,因为它包含换行符。
如果对我的正则表达式有任何改进,我将不胜感激。
发布于 2010-12-04 02:59:16
试一试
@"\\[Footnote[^\\]]*\\]";这应该在换行符之间匹配。也不需要将单个字符放入字符类中。
作为注释,多行正则表达式(没有字符串转义):
\[ # match a literal [
Footnote # match literal "Footnote"
[^\]]* # match zero or more characters except ]
\] # match ]在字符类([...])中,插入符号^具有不同的含义;它否定类的内容。因此,[ab]匹配a或b,而[^ab]匹配a或b以外的任何字符。
当然,如果你有嵌套的脚注,这将不起作用。像[Footnote foo [footnote bar] foo]这样的文本将从开头一直匹配到bar]。要避免这种情况,请将正则表达式更改为
@"\\[Footnote[^\\]\\[]*\\]";因此不允许使用左方括号或右方括号。当然,您只需要匹配最里面的脚注,并且必须将同一正则表达式应用两次(或更多,取决于最大嵌套级别)到整个文本,逐层“剥离”。
https://stackoverflow.com/questions/4348835
复制相似问题