Amit Kumar
Amit Kumar

Reputation: 5962

Find all char are enclosed with +

I have long string , now I need to find that in string each char (not digit) are enclosed with + sign.

For example

As you can see each char must with surrounded by +, to be true.

Note : Need to check only char between [a-zA-Z]. If there is no any alphabet in string then it should return true. (e.g : 1+1+1 or 1++.25,+5 will return true)

I'm trying to do with regex. but it's not working.

public static bool IsValidPattern(string str)
  {
     return Regex.IsMatch(str, @"\?\+[a-zA-Z]\+$");
  }

.NetFiddle

Upvotes: 3

Views: 78

Answers (2)

Igl3
Igl3

Reputation: 5108

Go the other way round and check if there is a char which is not enclosed in + with negative look ahead and look behind:

public static bool IsValidPattern(string str)
  {
     return !Regex.IsMatch(str, @"((?<!\+)[a-zA-Z])|([a-zA-Z]+(?!\+))");
  }

Fiddle here

Short explanation:

| : is an or so matching against ((?<!\+)[a-zA-Z]) or ([a-zA-Z](?!\+))

((?<!\+) is a negative lookbehind which assures that the following ([a-zA-Z]) is not preceded by a \+

((?!\+) is a negative lookahead which assures that the preceding ([a-zA-Z]) is not followed by \+

So the first alternative is matching strings like 'a+', 'c+' and so on and the second one the other way round ('+a', '+c') which is considered invalid.

Upvotes: 2

Jan
Jan

Reputation: 1975

Regexes have the advantege of being concise but can become quite cryptic and less maintainable at the same time.

Is there any reason why you don't want your code to clearly express what it's doing and to be able to add any other conditions in the future?

public static bool IsValidPattern(string str)
{
    for (int i = 0; i < str.Length; i++)
    {
        if (char.IsLetter(str[i]))
        {
            if (i == 0 || i == str.Length - 1 || str[i - 1] != '+' || str[i + 1] != '+')
            {
                return false;
            }
        }
    }

    return true;
}

Upvotes: 1

Related Questions