Reputation: 3694
How Can I forbid repeated characters using regular Expression?
This regular Expression should not allow
1--234567890
1--2345--1212
However following is valid
1-2-3-4-5-6-7-8-9-0
1234567890
The only concern here is minus cannot be entered after each other, so --
should not match
There is no restriction in how many dash are in string. I'm using C#
Thanks in Advance
Upvotes: 3
Views: 5458
Reputation: 17128
Use a negative lookahead: ^((.)(?!\2))+$
will match a string with no repeated characters.
Alternatively -- potentially faster: do a search for (.)\1
which will match a pair of repeated characters.
Upvotes: 2
Reputation: 499002
This would match any pair of identical characters:
"(.)\1"
Alternatively, for word characters:
"(\w)\1"
So, if the regex matches, you want to fail validation.
Update:
Now that you clarified that only --
is what you need to match on, here is another option:
"--"
Of course, you can simply use Contains("--")
on the string in such a case.
Upvotes: 4
Reputation: 64068
If a dash is the only character you care about:
// this regular expression is "inexact", three dashes always has two dashes, etc
var bad = new Regex("--");
if (bad.IsMatch(input))
{
throw new ArgumentException("Not a valid format", "input");
}
Or the far simpler:
// regular expression? no need
if (input.Contains("--"))
{
throw new ArgumentException("Not a valid format", "input");
}
Upvotes: 1
Reputation: 22379
This task is not suitable for regular expressions. What you probably want to do is write a loop that would go over the string and search for duplicates. The most efficient way of doing it is using some hash-based data structure like a dictionary.
Upvotes: 0