Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Regex to match any sentence but avoiding character repetition

Tags:

regex

I am looking for help to create a Regex to validates a string that satisfies these 4 criteria:

  1. The string must contain white space.
  2. The string must end with a full-stop/period.
  3. The string must have a minimum of 15 characters.
  4. The string must not contain a repetition of 3 or more characters. This is part I'm particularly struggling with.

For example:

Pass

  • One two three four.

Fail

  • OOOne two thee four.
  • One two thee fffour.
  • One two three four
  • One two three.
  • Onetwothreefour.

If possible could you explain how the regex is constructed to give me a better idea of how to construct them in future?


Here is what I've tried so far,

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

but I fear its not even close, please help.

like image 827
robbydarry Avatar asked Jan 12 '15 17:01

robbydarry


1 Answers

You can use this regex:

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

RegEx Demo

Explanation:

  • (?=\S*\s) - Lookahead to make sure there is at least one whitespace
  • (?!.*?(.)\1{2}) - Negative Lookahead to make sure there is no case of 3 consecutive characters
  • .{14,} to make sure there are at least 14 characters (15th being the last dot)
  • \.$ to make sure dot is always the last character
like image 170
anubhava Avatar answered Oct 01 '22 04:10

anubhava