简体   繁体   English

PHP Regex 在一定数量的字符后匹配句号

[英]PHP Regex match full stop after certain number of characters

I can't figure out how to do this with regex.我不知道如何用正则表达式来做到这一点。 I want to match a full stop after a certain number of characters in the sentence.我想在句子中一定数量的字符后匹配句号。

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.

It should not match the last full stop either.它也不应该与最后一个句号匹配。 It should match the second full stop in the first sentence and have no match in the second.它应该与第一句中的第二个句号匹配,而在第二句中没有匹配。 So the match should look like this:所以比赛应该是这样的:

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]

Is there a way to do it?有没有办法做到这一点? I have something along the lines of this which doesn't work at all:我有一些类似的东西根本不起作用:

/[.]{20,}/

As per your feedback ,根据您的反馈

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

pattern works for you.模式适合你。 See the regex demo .请参阅正则表达式演示

The idea is to find the line length, divide by 2 to get the char at the middle, and subtract 1 or 2 from the value obtained and use it in place of 30 in the limiting quantifier in the pattern above.这个想法是找到行长度,除以 2 得到中间的字符,然后从获得的值中减去 1 或 2,并用它代替上面模式中限制量词中的30

Pattern details图案详情

  • .{30,}? - any 30 chars other than line break chars or more, but as few as possible, - 除换行符以外的任何 30 个字符或更多,但尽可能少,
  • \\K - match reset operator that omits the text matched so far \\K - 匹配重置操作符,忽略目前匹配的文本
  • \\. - a dot - 一个点
  • (?=.{30,}) - a positive lookahead that requires the presence of at least 30 any chars other than line breaks immediately to the right of the current location. (?=.{30,}) - 一个正向前瞻,要求在当前位置的右侧出现至少 30 个除换行符以外的任何字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM