【问题标题】:regex php look ahead number正则表达式 php 前瞻数字
【发布时间】:2021-11-20 23:47:49
【问题描述】:

堆垛机!

我一直在尝试解决这个问题,但没有运气。
(.*?(?:\.|\?|!))(?: |$)

上面的模式是捕捉和打断段落中的所有句子,并以标点符号结尾。
例子

  1. 今天是最伟大的。你是最伟大的。

比赛回来了三个

Match {  
  1.    
  Today is the greatest.   
  You are the greatest.   
}

但是,当有一个带句号的数字时,我试图让它不中断,并希望看到以下匹配:

Match {  
  1.Today is the greatest.   
  You are the greatest.   
}

提前感谢您的帮助

【问题讨论】:

  • 所以你有很多句子并且想要将它们分开 - 由.(点)分隔?在某些句子中,1.2. 打破了这种模式?
  • 没错就是这样
  • 我想出了以下 ^(?=\d\s?\.\s?)(.)+$ 但仍然不完整
  • 另一个使用 preg_split 的想法:preg_split('~[.!?](?<!\d.)\s+~', $str) 请注意,例如。 Mr. 等等。它需要自然语言处理,才能准确地标记成句子。

标签: php regex


【解决方案1】:

使用

.*?[.?!](?=(?<!\d\.)\s+|\s*$)

regex proof

解释

--------------------------------------------------------------------------------
  .*?                      any character except \n (0 or more times
                           (matching the least amount possible))
--------------------------------------------------------------------------------
  [.?!]                    any character of: '.', '?', '!'
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
      \d                       digits (0-9)
--------------------------------------------------------------------------------
      \.                       '.'
--------------------------------------------------------------------------------
    )                        end of look-behind
--------------------------------------------------------------------------------
    \s+                      whitespace (\n, \r, \t, \f, and " ") (1
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
   |                        OR
--------------------------------------------------------------------------------
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
--------------------------------------------------------------------------------
  )                        end of look-ahead

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2010-12-17
    • 1970-01-01
    相关资源
    最近更新 更多