Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi ,

I am writing console application which will check for word whether it is Palindrome or not. But i dont know how to do it using regular expression can you please suggest for the same. also wanted to ignore none-alphanumeric characters.

Eg. Mad&**am is a palindrome


Thanks

What I have tried:

static void Main(string[] args)
{
string s, revs = "";
Console.WriteLine(" Please Enter a string value");
s = Console.ReadLine();
for (int i = s.Length - 1; i >= 0; i--)
{
revs += s[i].ToString();
}
//string checking for pallindrome
if (revs == s)
{
Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
else
{
Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
Console.ReadKey();
}
Posted
Updated 17-Jun-16 23:53pm
v3

1 solution

Don't even try.
A regex is definitely the wrong tool for that. You could do it, but it'd be horrible.
Instead, just do it in C# code.
By a total coincidence, I wrote this yesterday for someone else:
C#
private static bool IsPalindrome(string inputString)
    {
    char[] inputArray = inputString.ToLowerInvariant().Where(char.IsLetter).ToArray();
    int len = inputArray.Length;
    for (int i = 0; i < len / 2; i++)
        {
        if (inputArray[i] != inputArray[len - (i + 1)]) return false;
        }
    return true;
    }
 
Share this answer
 
Comments
Torakami 18-Jun-16 6:31am    
Thanks for answer , but can you explain me why not to go for regex ?
OriginalGriff 18-Jun-16 6:48am    
Because regexes are text processors, they don't include any logical operations. So they can return a "match / didn't match" result, but they really aren't good at "ignore all characters except these types, and then match them up in pairs (unless it's the center one of the non-matched characters if there are an odd number of those)" type decisions. So while it can be done, the actual regex would be horrible, both the look at, to understand, and to modify. If you want to go for it, then do:
http://www.ultrapico.com/Expresso.htm
will help you, but I seriously wouldn't recommend it. It will take quite a lot of time and effort to get it working.
Just because something is possible, doesn't mean you should do it! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900