【问题标题】:Regex matching with line breaks正则表达式匹配换行符
【发布时间】:2010-10-11 03:10:46
【问题描述】:

如何匹配可以在任何地方发生换行符的正则表达式?

例如,如果我要匹配“千龟蛋”,它应该匹配以下所有情况。 (甚至是换行符在单词内的情况。)

Scientists have revealed that a mammoth effort to move *thousands of turtle eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles.   

Scientists have revealed that a mammoth effort to move *thousands 
of turtle eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles.

Scientists have revealed that a mammoth effort to move *thousands of 
turtle eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles.

Scientists have revealed that a mammoth effort to move *thousands of turtle 
eggs* from beaches around the Gulf of Mexico after the Deepwater Horizon oil spill may have saved almost 15,000 of the reptiles.

【问题讨论】:

  • 下一次,请向我们提供有关您正在使用哪个正则表达式库或哪个应用程序的信息,因为不同的库/应用程序会给出不同的正确答案。您还可以通过选择多个适当的标签来发出信号。
  • @Vantomex 正则表达式库重要吗?我可以用一个通用的答案来做,而不是绑定到任何库/应用程序。 - 谢谢
  • 并非每个正则表达式库都支持所有格量​​词、原子分组等。它们可用于优化库的正则表达式解析速度。此外,为了在正则表达式库之间实现相同的结果,它们存在许多规则差异。

标签: regex


【解决方案1】:
  /thousands\s+of\s+turtle\s+eggs/

或此版本以确保 thousandseggs 不是另一个单词的一部分(如 ...eggsbath

  /\bthousands\s+of\s+turtle\s+eggs\b/

【讨论】:

  • 单词中可能出现换行的情况怎么办?
  • 只需在字母之间添加这种可能性:/\bt[\r\n]*h[\r\n]*o[\r\n]*...
【解决方案2】:

您可以使用标志“s”来匹配所有换行符。

如果您使用正则表达式“/reptiles..*?sc/gis”,它将匹配“reptiles.sc”

你可以试试这个link

这是一个在线正则表达式编辑器

【讨论】:

    【解决方案3】:

    使用“s”开关。然后 ^$ 成为整个字符串的开始和结束,换行符被认为是空格。所以只要你使用 \s 来匹配单词之间的间隙。 例如:

    #thousands\sof\sturtle\seggs#si

    【讨论】:

    • 对不起,你已经走远了。换行符总是被认为是空白,\s 总是匹配它们。 s 开关的作用是允许 dot (.) 匹配换行符,默认情况下它不这样做。这最初(不幸的是)称为 single-line 模式,但现在更常见的是 dot-matches-allDOTALL 模式。 s 开关对锚(^$)没有影响。有关详细信息,请参阅本教程的“点”和“锚”部分:regular-expressions.info/tutorial.html
    • 谢谢。我不知道,我只是假设这是我提到的方式。我会调查的。 :)
    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多