5 Replies - 498 Views - Last Post: 16 August 2011 - 05:51 PM

#1 Skaggles   User is offline

  • THE PEN IS MIGHTIER
  • member icon





Reputation: 255
  • View blog
  • Posts: 641
  • Joined: 01-March 09

Check that string is alphanumeric with regex

Posted 27 October 2010 - 02:00 AM

Description: See the example application usage below at the bottom of the code snippet.A string extension method that uses regex to check if the string is alphanumeric.
using System.Text;
using System.Text.RegularExpressions;

public static class StringExtensions
{
    public static bool IsAlphanumeric(this string source)
    {
        Regex pattern = new Regex("[^0-9a-zA-Z]");
        return !pattern.IsMatch(source);
    }
}

// EXAMPLE USAGE

class Program
{
    static void Main(string[] args)
    {
        string testString = Console.ReadLine();

        if (testString.IsAlphanumeric())
            Console.WriteLine("Yep!");
        else
            Console.WriteLine("Nope!");

        Console.ReadKey(); // Wait for key before exiting
    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: Check that string is alphanumeric with regex

#2 Brandon_R   User is offline

  • New D.I.C Head

Reputation: 14
  • View blog
  • Posts: 46
  • Joined: 08-January 11

Re: Check that string is alphanumeric with regex

Posted 09 January 2011 - 06:48 AM

That's really nice.
Was This Post Helpful? 0
  • +
  • -

#3 usipime   User is offline

  • New D.I.C Head

Reputation: -5
  • View blog
  • Posts: 3
  • Joined: 25-September 10

Re: Check that string is alphanumeric with regex

Posted 24 February 2011 - 12:13 AM

I think it's return pattern.IsMatch(source) and not !pattern.IsMatch(source) because it checks if the string is alphanumeric it should print "Yep!" if not it should print "Nope!" but your code does the opposite.
Was This Post Helpful? 0
  • +
  • -

#4 Brandon_R   User is offline

  • New D.I.C Head

Reputation: 14
  • View blog
  • Posts: 46
  • Joined: 08-January 11

Re: Check that string is alphanumeric with regex

Posted 12 March 2011 - 04:49 PM


Was This Post Helpful? 0
  • +
  • -

#5 Brandon_R   User is offline

  • New D.I.C Head

Reputation: 14
  • View blog
  • Posts: 46
  • Joined: 08-January 11

Re: Check that string is alphanumeric with regex

Posted 12 March 2011 - 04:55 PM

Good Job
Was This Post Helpful? 0
  • +
  • -

#6 ad3285   User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 3
  • Joined: 15-August 11

Re: Check that string is alphanumeric with regex

Posted 16 August 2011 - 05:51 PM

usipime: that's because of his Regex pattern. Your statement will hold true if his Regex pattern is [0-9a-zA-Z] instead of [^0-9a-zA-Z]
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1