A regular expression matches any sentence, but avoids the repetition of characters

I am looking for help to create a regex for checking a string that satisfies these 4 criteria:

  • The string must contain a space.
  • The line should end with a full stop / period.
  • The string must contain at least 15 characters.
  • The string must not contain a repetition of 3 or more characters. This is the part that I am especially struggling with.

For instance:

Pass

  • One two three four.

Renouncement

  • OOOne two thee four.
  • Two of your affairs.
  • One two three four
  • Two three.
  • Onetwothreefour.

If possible, could you explain how the regex is built to give me a better idea of โ€‹โ€‹how to build them in the future?


Here is what I have tried so far,

^(.*?={15,})(\.\Z)$ 

but Iโ€™m afraid that it wonโ€™t even close, please help.

+5
source share
1 answer

You can use this regex:

 ^(?=\S*\s)(?!.*?(.)\1{2}).{14,}\.$ 

RegEx Demo

Explanation:

  • (?=\S*\s) - Lookahead to make sure there are at least one spaces.
  • (?!.*?(.)\1{2}) - Negative Lookahead to make sure there is no case with three consecutive characters.
  • .{14,} to make sure there are at least 14 characters (the 15th last dot)
  • \.$ to make sure the dot is always the last character
+8
source

Source: https://habr.com/ru/post/1210921/


All Articles