0

I want to validate a string in such a manner that in that string, if a "-" is present it should have an alphabet before and after it. But I am unable to form the regex pattern.

Can anyone please help me for the same.

2
  • what else can be there in the string Commented Nov 26, 2014 at 11:40
  • can there be more than one pattern in the string that needs to be validated? Commented Nov 26, 2014 at 12:45

3 Answers 3

1

Rather than using a regex to check this I think I would write an extension method using Char.IsLetter(). You can handle multiple dashes then, and use languages other than English.

public static bool IsValidDashedString(this String text)
{
    bool temp = true;

    //retrieve the location of all the dashes
    var indexes =  Enumerable.Range(0, text.Length)
            .Where(i => text[i] == '-')
            .ToList();

    //check if any dashes occur, if they are the 1st character or the last character
    if (indexes.Count() == 0 ||
        indexes.Any(i => i == 0) ||
        indexes.Any(i => i == text.Length-1))
    {
        temp = false;
    }
    else //check if each dash is preceeded and followed by a letter
    {
        foreach (int i in indexes)
        {
            if (!Char.IsLetter(text[i - 1]) || !Char.IsLetter(text[i + 1]))
            {
                temp = false;
                break;
            }
        }
    }

    return temp;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The following will match a string with one alphabetic character before the "-" and one after:

[A-z]-[A-z]

You may need to first test whether there is "-" present if that is not always the case. Could do with more information about the possible string contents and exactly why you need to perform the test

Comments

0
(^.+)(\D+)(-)(\D+)(.+)

I have tested this for some examples here http://regexr.com/39vfq

Comments

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.