1

I want to have a regex expression do that.

  • string = 12345 => true
  • string = 11145 => false, because we do not allow any character appear consecutively, this example is the 1.
  • string = aaa664 => false, it is because of a.

I need regex to do it for both character and digit, please help.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
user2617403
  • 387
  • 1
  • 5
  • 16
  • You may find an answer in this one also - http://stackoverflow.com/questions/12870489/regex-to-match-a-word-with-unique-non-repeating-characters? – murtazat May 04 '15 at 05:04
  • 1
    @murtazat That's not the same as this one. You can have duplicate character as long as they are not consecutive. – Haochen Wu May 04 '15 at 05:36

4 Answers4

2
^(?!.*(.)\1+).*$

This should so it for you.See demo.The lookahead makes sure there is no . which is repeated again.

https://regex101.com/r/uE3cC4/21

vks
  • 67,027
  • 10
  • 91
  • 124
0

You can generally use a capture group and back reference to detect consecutive characters. For example, in grep:

$ echo abc | grep '\([a-z]\)\1'

$ echo abbc | grep '\([a-z]\)\1'
abbc

The parentheses around the thing you're looking for capture the resultant matching portion and this portion is then substituted for \1 in the remainder of the regex.

In terms of your specific test cases, see below:

$ echo 12345 | grep '\([a-zA-Z0-9]\)\1' >/dev/null; echo $?
1
$ echo 11145 | grep '\([a-zA-Z0-9]\)\1' >/dev/null; echo  $?
0
$ echo aaa664 | grep '\([a-zA-Z0-9]\)\1' >/dev/null; echo $?
0

You can see you get 1 for a successful string, 0 for a bad one (that matches the regex).

Depending on what language you're using, the methods to detect a match or not may change slightly but the overall concept of capture group and back reference should be the same.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

If your regex allows negation, just negate the match of (.)\1

Given:

$ echo "$e"
12345 => true
11145 => false
aaa664 => false

Now with perl, only print if no match to (.)\1:

$ echo "$e" | perl -lne 'print if !/(.)\1/'
12345 => true

(or $ echo "$e" | perl -lne 'print unless /(.)\1/')

Same thing with sed:

$ echo "$e" | sed -n '/\(.\)\1/!p'
12345 => true

grep:

$ echo "$e" | grep -v '\(.\)\1'
12345 => true

If you do not negate the match, the lines that do have repeated letters with print:

$ echo "$e" | grep  '\(.\)\1'
11145 => false
aaa664 => false
dawg
  • 98,345
  • 23
  • 131
  • 206
0
    if (preg_match('/(.)\\1{2}/', $value)) {
    return 'NOT OK';   //invalid
    } else {
    return 'OK';  //valid
    }

here is the answer!

user2617403
  • 387
  • 1
  • 5
  • 16
  • Your answer will detect any character repeated 3 times in a row, but not twice in a row - Are you sure that is what you want? – nhahtdh May 05 '15 at 03:37