3

I need a Regex to accept the input only following possible cases like

1.It start with characters only [a-zA-Z]

2.It may contains numbers but it may not repeated 3 or moretimes.

Example:

akjsjdfljsfjl133113 Valid

123123sfsf not valid

asfsdf1111asdf notvalid adf111 not valid

I have tried this code

$input_line="sfjs123232";
preg_match("/^[a-zA-Z](\d)\1{2,}/", $input_line, $output_array);
5
  • Why is adf111 not valid? Commented May 13, 2014 at 4:34
  • because 1 is repeated 3 times Commented May 13, 2014 at 4:36
  • Rule 2 was that it may not be repeated 3 or more times. Commented May 13, 2014 at 4:41
  • 1
    FYI, they may be gently pulling your leg: strictly speaking, repeated three times means that it is present four or more times (the first instance, then the three repeats.) :) Commented May 13, 2014 at 4:43
  • Is a121212121212 acceptable? The digits 1 and 2 are repeated many times in the string. If it is acceptable and you only meant not repeated consecutively, then I misunderstood the question. Commented May 13, 2014 at 5:00

1 Answer 1

4

You can use a Negative Lookahead here.

^[a-zA-Z]+(?:(?!.*(\d)\1{2,}).)*$

See Live demo

Regular expression

^                the beginning of the string
[a-zA-Z]+        any character of: 'a' to 'z', 'A' to 'Z' (1 or more times)
(?:              group, but do not capture (0 or more times)
 (?!             look ahead to see if there is not:
  .*             any character except \n (0 or more times)
  (              group and capture to \1:
   \d            digits (0-9)
  )              end of \1
   \1{2,}        what was matched by capture \1 (at least 2 times)
  )              end of look-ahead
  .              any character except \n
 )*              end of grouping
$                before an optional \n, and the end of the string
Sign up to request clarification or add additional context in comments.

3 Comments

What about a121212121212? Your regex matches that. But I probably misunderstood the problem: I thought it was about digits not appearing 3 times anywhere in the string. This is the problem that I don't know how to solve without using infinite lookbehinds (not available in PHP).
I see that your interpretation was right: he said that akjsjdfljsfjl133113 is a valid string, even though it has 3 1s. +1 :)
@zx81 He meant the same digit repeated 3 times as in abc111def

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.