【问题标题】:PHP Regex match full stop after certain number of charactersPHP Regex 在一定数量的字符后匹配句号
【发布时间】:2017-09-28 10:31:11
【问题描述】:

我不知道如何使用正则表达式来做到这一点。我想在句子中一定数量的字符后匹配句号。

this is a long sentence. it contains a few full stops in it. I want to match the full stop after the halfway point.

this sentence is shorter. it also contains full stops but not many.

它也不应该与最后一个句号匹配。它应该匹配第一句中的第二个句号,而第二句中没有匹配。所以比赛应该是这样的:

this is a long sentence. it contains a few full stops in it[.] I want to match the full stop after the halfway point.

this sentence is shorter. it also contains full stops but not many.   [no match]

有办法吗?我有一些类似的东西根本不起作用:

/[.]{20,}/

【问题讨论】:

  • 这听起来很模糊。见.{30,}?\K\.(?=.{30,}),它只会匹配30个或更多字符后的点,如果它后面有30个或更多字符。
  • 这很快,我什至还没有完成编辑问题。那是不匹配吗?它实际上是用于 preg_split。
  • Wiktor Stribiżew 解决方案效果很好
  • @Hasen .{30,}?\K\.(?=.{30,}) 真的适合你吗?我的意思是,它并没有真正将线条分成两部分,它只是匹配 30 个字符之外的 .。见regex101.com/r/P6JIa5/3。我还是不明白要求。
  • 我可以先用php计算每个句子的中间点,得到当前30的值,问题是它真的需要用preg_split将那个点的句子分成两部分。我想我的问题并不清楚,我认为这就是我要问的。我想我需要某种 (pattern)+(pattern) 来获得句子的两个部分。

标签: php regex preg-replace preg-match preg-split


【解决方案1】:

根据your feedback

.{30,}?\K\.(?=.{30,})

模式适合你。请参阅regex demo

想法是找到行长,除以2得到中间的char,然后从得到的值中减去1或2,并用它代替上面模式中限制量词中的30

模式详情

  • .{30,}? - 除换行符以外的任何 30 个字符或更多,但尽可能少,
  • \K - 匹配重置运算符,忽略目前匹配的文本
  • \. - 一个点
  • (?=.{30,}) - 一个积极的前瞻,需要在当前位置的右侧至少存在 30 个除换行符以外的任何字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多