Flood Gravemind
Flood Gravemind

Reputation: 3803

Regex to limit the number of occurrences of a particular character in a string

Is it possible using only regex to limit the number of occurrences of specific characters in a string?

For example, I want to limit the number of occurrences of $ or % or space in a string to 5 occurrences max.

Is this possible?

Upvotes: 3

Views: 6310

Answers (2)

Konrad Kokosa
Konrad Kokosa

Reputation: 16898

In general, you must split your problem into two different aspects:

  1. How to check if some constraint is satisfied (like, for example, if number of occurrences of $ character is no greater than 5)
  2. How to force that constraint

To solve 1. problem, you can of course use Regex. Regular expression \d{6,} for example can check if there is 6 or more digits.

To solve 2. problem, C# do not have generic method for this. Simply speaking, there must be something that is forcing the constraints. The simplest way is to create class with properties that checks constraints on setting (so it is the property that is forcing the constraint):

public class SomeTestClass
{
    private string text;
    public string Text 
    { 
        get
        {
            return text;
        }
        set
        {
            CheckConstraints(value, "Text");
            text = value;
        }
    }

    private void CheckConstraints(string value, string param)
    {
        if (Regex.IsMatch(value, @"\d{6,}"))
        {
            throw new ArgumentException("Argument do not match the constraint", param);
        }
    }
}

As text is private, there is no other way of setting it than by property, which checks your constraints. This of course can be further improved, for example by creating sets of reusable rules etc.

If there is other object that manages your class - for example some Data Provider that manages Data Entities, you can use attributed approach.

Upvotes: 4

try this expression. In this case, the character you're limiting is A

/^([^A]*A[^A]*){0,5}$/

http://rubular.com/r/X5iz5dHzgs

Upvotes: 9

Related Questions