<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C# Help &#187; Regex</title>
	<atom:link href="http://www.csharphelp.com/tag/regex/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.csharphelp.com</link>
	<description>C# Tutorial and Guides</description>
	<lastBuildDate>Tue, 07 Feb 2012 01:03:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Masked Edit Control in C# using Regex</title>
		<link>http://www.csharphelp.com/2007/05/masked-edit-control-in-c-using-regex/</link>
		<comments>http://www.csharphelp.com/2007/05/masked-edit-control-in-c-using-regex/#comments</comments>
		<pubDate>Sun, 20 May 2007 01:58:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Regex]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=1738</guid>
		<description><![CDATA[By Michael J. Bullard We programmed a masked textbox control with C# that will convert the mask into a regular expression for each character in the field. It is designed to accept a user defined mask or a regular expression that defines each character in the field. If you pass it the mask as a string [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size: 10pt;">By Michael J. Bullard</span></p>
<p><span style="font-size: 10pt;">We programmed a masked textbox control with C# that will convert the mask into a regular expression for each character in the field. It is designed to accept a user defined mask or a regular expression that defines each character in the field. If you pass it the mask as a string using the characters listed below, it will build the regular expression for you. It then loads the regular expression into an array which is used to validate and control the behavior of the field. There is an error provider message and a tooltip associated with the control.</p>
<p>The m_mask property is used to set the mask variable. Masks are set up for each character. Examples of valid mask strings and the regular expression they generate are detailed below:</p>
<pre>           # = [0-9]
           9 = [\s0-9]
           A = [A-Z]
           a = [a-z]
           B = [A-Za-z]
           C = [A-Za-z0-9]
           M
           D
           Y
           / * , . - : ( ) { } = +</pre>
<p>Examples:If you set YourTextBox.m_mask = &#8220;9,999,999,999.99&#8243; then the field is set to accept only numeric characters and the 2 digit numbers will be less than 10 Trillion in length. Negative signs are displayed to the left of the number. Commas will be inserted into the number when you leave the field. Entering the field removes the commas and selects the entire number. Inserting and backspacing work to help you edit existing numbers.</p>
<p>If you set YourTextBox.m_mask = &#8220;9,999,999,99#.##&#8221; then the behavior of the field will be the same as above except that 0.00 is diplayed when you enter the field and the digits will be filled with zeros, if blank, when you leave the field. The &#8220;9&#8243; characters will be a space if not filled in.</p>
<p>If you set YourTextBox.m_mask = &#8220;(###)###-####&#8221; then the literals appear in the textbox when you enter a blank field. The textbox will accept numeric characters in the non literal positions. Inserting and backspacing work to help you edit existing numbers.</p>
<p>If you set YourTextBox.m_mask = &#8220;AaBC&#8221; then the first position will accept all upper case letters, the second position will accept all lower case letters, the third position will accept all upper and lower case letters and the fourth position will accept all letters and all numbers.</p>
<p>If you set YourTextBox.m_mask = &#8220;[A-JL-Z][012]-[6-9]/[jklm]&#8221; the first position will accept all upper case letters except K, the second position will accept only 0, 1 or 2, the third position will be equal to a literal dash, the fourth position will accept numbers of 6 through 9, the fifth position will be a literal forward slash and the last position will accept only lower case j, k, l or m.</p>
<p>The M, D and Y are designed to provide masks of &#8220;MM/DD/YYYY&#8221; or &#8220;MM/DD/YY&#8221;. You could also rearrange the date to show the year first. The first M position will accept only 0 or 1. The first D position will accept only 0, 1, 2 or 3. The first Y position will accept only 0, 1 or 2 if there are four Y characters. The second Y position will accept 0 through 5 and 9 if there are only two Y characters. The second Y position will accept only 9 or 0 if there are four Y characters.</p>
<p>Additionally, an Error-Provider displays when the character entered does not match the regular expression. The mouse-hover event can be used on the form to display the string YourTextBox.stip as a tool-tip.</p>
<pre style="font-size: 8pt; color: #000000; font-family: Verdana, Arial;">private void MaskText_Enter(object sender, System.EventArgs e)
{
  isleaving = false;
  EditRegx sd = (EditRegx) sender;
  string s = this.Text;
  int iSLength = s.Length;

  //**public class ETMFein : ETMString
  this.m_mask = "[A0-9][A0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]";
  alphas = literals = true;
  sTip = "Enter a Federal ID number in ##-####### format";
  //**public class ETMMedSupID : ETMString
  this.m_mask = "[10][20][30][40][50][60][70]";
  alphas = true;
  sTip = "Enter a Med Sup ID";

  //**public class ETMZipCode : ETMString
  this.m_mask = "[A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9][A-Z0-9][\s-][\s0-9][\s0-9][\s0-9][\s0-9]";
  alphas = literals = true;
  sTip = "Enter a Zip Code in #####-#### format";
  //**public class ETMPhoneNumber : ETMString
  this.m_mask = "[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]-[\s0-9][\s0-9][\s0-9][\s0-9][\s0-9][\s0-9][\s0-9]";
  alphas = literals = true;
  sTip = "Enter a Phone Number in ###-###-####-####### format";
  //**public class ETMDecimal : ETMNumber
  this.m_mask = "999,999,999,999";
  isdigit = true;
  sTip = "Enter a Number with No Decimals";

  //**public class ETMPercent : ETMDecimal
  this.m_mask = "999,999,999,999.###%";
  isdigit = true;
  sTip = "Enter a Percent with Three Decimals";

  //**public class ETMDollar : ETMDecimal
  this.m_mask = "9,999,999,999,99#.##";
  isdecimal = true;
  sTip = "Enter a Dollar Value with Two Decimals";

  //**public class ETMNumber_1Dec : ETMDecimal
  this.m_mask = "99,999,999,999,99#.#";
  isdecimal = true;
  sTip = "Enter a Number with One Decimal";

  //**public class ETMNumber_2Dec : ETMDecimal
  this.m_mask = "9,999,999,999,99#.##";
  isdecimal = true;
  sTip = "Enter a Number with Two Decimals";

*/
//*********************************************************************
  int iMaskLength = sd.mask.Length;
  if((isdecimal)||((isdigit)&amp;&amp;!(alphas)&amp;&amp;!(literals)))
  {
    string sdecdig = Trimit(s);
    if(negpressed)
      sdecdig = "-" + sdecdig;
    this.Text = sdecdig;
  }
  this.SelectAll();
  string strmask = this.mask;
  int numLiteral = setMaskArray(strmask);
  if((isdecimal)||((isdigit)&amp;&amp;!(alphas)&amp;&amp;!(literals)))
  {
    this.etmlength = this.regexArray.Count - numLiteral;
  }
  else
  {
    this.etmlength = this.regexArray.Count;
  }
  this.MaxLength = etmlength;

    //set the cursor in the blank mask and set alphas and isdigit flags
    //new alphas should position cursor after first literal.
    //digits and decimals should position cursor before dot
    //if digits and not alphas then right align
  int inumdec = 0;
  int cursorpos = 0;
  int firstalpha = 0;
  int literalpos = 0;
  if((iSLength &lt;1)&amp;&amp;(iMaskLength &gt;=1)) //entering a blank cell, display mask
  {
    for(int i = 0; i&lt;1

  if((isdigit||isdecimal)&amp;&amp;(!alphas)&amp;&amp;(!literals))
  {
    this.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
  }
  if((alphas||literals)&amp;&amp;(!isdecimal))
  {
    this.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
  }

  if((iSLength &lt;1)&amp;&amp;(iMaskLength &gt;=1)) //entering a blank cell, display mask
    {
      string sMaskText = setBlankMaskText();
      this.Text = sMaskText;
    if((isdecimal)&amp;&amp;(!alphas)&amp;&amp;(!literals))
    {
      cursorpos = this.Text.IndexOf(".");
    }
      sd.setCursor = cursorpos;
      this.Select(sd.setCursor, 0);
    }
    if((iSLength &gt;=1)&amp;&amp;(iMaskLength &gt;=1)&amp;&amp;(alphas||literals)) //entering a non blank cell, display mask
    {
      string sMaskText = setMaskText(s);
      this.Text = sMaskText;
      this.SelectAll();
    }

}// end of MaskText_Enter

// *****************************************************************
    private void MaskText_MouseHover(object sender, System.EventArgs e)
    {

      EditRegx sd = (EditRegx) sender;
      ToolTip toolTip1 = new ToolTip();
      toolTip1.AutoPopDelay = 3000;
      toolTip1.InitialDelay = 1000;
      toolTip1.ReshowDelay  = 2000;
      toolTip1.ShowAlways = true;

      toolTip1.SetToolTip(sd, this.sTip);

    }

// ************************************************************
    private string setBlankMaskText()
    {
      string sBlankMask = "";
      string sWork1 = "";
      string sWork2 = "";
      int iArrayLen = this.regexArray.Count;
      int i = 0;
      int iFirstTime = 999;
      if((alphas)||(literals))
      {
        for(i = 0; i &lt; iArrayLen; i++)
        {
          sWork1 = (string)regexArray[i];
          if((sWork1.StartsWith("L"))&amp;&amp;(sWork1.Substring(1,1)!= ","))
          {
            sWork2 = sWork2 + sWork1.Substring(1, sWork1.Length - 1);
          }
          else
          {
            sWork2 = sWork2 + " ";
            if(iFirstTime == 999)
            {
              iFirstTime = i;
            }
          }
          sBlankMask = sWork2;
          if(iFirstTime != 999)
          {
            this.setCursor = iFirstTime;
          }
          else
          {
            this.setCursor = 0;
          }
        }//end of for loop
      }//end of alphas
      if((isdigit)&amp;&amp;!(isdecimal)&amp;&amp;!(alphas)&amp;&amp;!(literals))
      {
        sBlankMask = "";
        setCursor = 0;
      }
      if((isdigit)&amp;&amp;(isdecimal)&amp;&amp;!(alphas)&amp;&amp;!(literals))
      {
        sBlankMask = ".";// + sdecimal;
        setCursor = 0;
      }

      return sBlankMask;
    }
//*****************************************
    private string setMaskText(string x)
    {
      string sMask = "";
      string sWork1 = "";
      string sWork2 = "";
      string s = x;
      string sTrimmed = Trimit(s);
      int iTrimLen = sTrimmed.Length;
      int iArrayLen = this.regexArray.Count;
      int ia = 0;
      int it = 0;
      if((alphas)||(literals))
      {
        for(ia = 0; ia &lt; iArrayLen; ia++)
        {
          sWork1 = (string)regexArray[ia];
          if(sWork1.StartsWith("L"))
          {
            sWork2 = sWork2 + sWork1.Substring(1, sWork1.Length - 1);
          }
          else if(it &lt; iTrimLen)
          {
            sWork2 = sWork2 + sTrimmed.Substring(it,1);
            it = it + 1;
          }
          else
          {
            sWork2 = sWork2 + " ";
          }
        }//end of for loop
        sMask = sWork2;
      }//end of alphas
      if((isdigit)&amp;&amp;!(isdecimal)&amp;&amp;!(alphas)&amp;&amp;!(literals))
      {
        sMask = sTrimmed;
      }
      if((isdecimal)&amp;&amp;!(alphas)&amp;&amp;!(literals))
      {
        s = sTrimmed;
        int whereisdot = sTrimmed.IndexOf(".");
        if(whereisdot == -1)
        {
          sTrimmed = sTrimmed + ".";
          whereisdot = sTrimmed.IndexOf(".");
        }
        //if(!dotpressed)
        //{
        //  setCursor = whereisdot;
        //}
        //else
        //{
        //  setCursor = sTrimmed.Length;
        //}
        sMask = sTrimmed;
      }
      return sMask;
    }  //end of setMaskText

//*******************************************
    public int setMaskArray(string s)
    {
      int numL = 0;
      int numM = 0;
      int numD = 0;
      int numY = 0;
      int totY = 0;
      string strmask = s;
      int masklen = strmask.Length;

      ArrayList workArray1 = new ArrayList();
      string[] workArray2 = new string[masklen];
      string strWork  = "";
      string strWork1 = "";
      string strWork2 = "";
      int x = 0;
      for( int i = 0; i &lt; masklen; i++)
      {
        strWork1 = "";
        strWork2 = "";
        strWork = strmask.Substring(i,1);
        if(strWork == "#")
        {
          strWork1 = "[0-9]";
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if(strWork == "9")
        {
          strWork1 = "[\s0-9]";
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if(strWork == "A")
        {
          strWork1 = "[A-Z]";
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if(strWork == "a")
        {
          strWork1 = "[a-z]";
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if(strWork == "B")
        {
          strWork1 = "[A-Za-z]";
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if(strWork == "C")
        {
          strWork1 = "[A-Za-z0-9]";
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }

        else if(strWork == "M")
        {
          if(numM == 0)
          {
            strWork1 = "[0-1]";
            numM = 1;
          }
          else if(numM &gt;= 1)
          {
            strWork1 = "[0-9]";
            numM = 2;
          }
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if(strWork == "D")
        {
          if(numD == 0)
          {
            strWork1 = "[0-3]";
            numD = 1;
          }
          else if(numD &gt;= 1)
          {
            strWork1 = "[0-9]";
            numD = 2;
          }
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if(strWork == "Y")
        {
          if(numY == 0)//Y
          {
            totY = masklen - i;
            if(totY == 2)
            {
              strWork1 = "[0-59]";
            }
            else
            {
              strWork1 = "[0-2]";
            }
            numY = 1;
          }
          else if(numY == 1)//yY
          {
            if(totY == 2)
            {
              strWork1 = "[0-9]";
            }
            else
            {
              strWork1 = "[09]";
            }
            numY = 2;
          }
          else  //yyYorY
          {
            strWork1 = "[0-9]";
            numY = numY + 1;
          }
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
        }
        else if((strWork == "/")||(strWork == "*")||(strWork == ",")||(strWork == ".")
          ||(strWork == "-")||(strWork == ":")||(strWork == "(")||(strWork == ")")
          ||(strWork == "{")||(strWork == "}")||(strWork == "=")||(strWork == "+"))
        {
          strWork1 = strWork;
          strWork1 = "L" + strWork1;
          workArray1.Add(strWork1);
          workArray2[x] = strWork1;
          x = x + 1;
          numL = numL + 1;
        }
        else if(strWork == "[")
        {
          int remaining =  masklen - i;
          int test = 0;
          for(int r = 0; r &lt; remaining; r++)
          {
            test = i + r;
            strWork1 = strmask.Substring(test,1);
            strWork2 = strWork2 + strWork1;
            if(strWork1 == "]")
            {
              i = test;
              break;
            }
          }
          if(strWork2.EndsWith("]"))
          {
            workArray1.Add(strWork2);
            workArray2[x] = strWork2;
            x = x + 1;
          }
          else
          {
            MessageBox.Show("error reading Mask, no closing bracket ]");
          }
          //i = test;  //already did this
        }//end of else if starts with "["
      }//end of big For Loop

      int j = workArray1.Count;
      int k = workArray2.Length;
      string[] workArray = new string[j];
      for(int y = 0; y &lt; workArray1.Count; y++)
      {
        workArray[y] = (string)workArray1[y];
      }
      this.regexArray.Clear();
      this.regexArray.AddRange(workArray);
      int l = this.regexArray.Count;
      return numL;
    }//end of setMaskArray

//*******************************************
    private string GetKeyRegEx(int startcaret)
    {
      int iPos = startcaret;
      int iSizeRegExArray = this.regexArray.Count;//not set to instance of object, called from text changed
      string sReturnRegEx = "";
      if((iPos &lt; iSizeRegExArray)&amp;&amp;(iPos != -1))
      {
        sReturnRegEx = (string)regexArray[iPos];
      }
      else
      {
        sReturnRegEx = "TooFar";//this.regexArray[iSizeRegExArray - 1];
      }
      return sReturnRegEx;
    }</pre>
<p></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/05/masked-edit-control-in-c-using-regex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C# Strings and Regular Expressions</title>
		<link>http://www.csharphelp.com/2007/05/c-strings-and-regular-expressions/</link>
		<comments>http://www.csharphelp.com/2007/05/c-strings-and-regular-expressions/#comments</comments>
		<pubDate>Sun, 13 May 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Regex]]></category>
		<category><![CDATA[Strings]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=542</guid>
		<description><![CDATA[3.0. Introduction It would be very rare to create an entireapplication without using a single string. Strings help make sense ofthe seemingly random jumble of binary data that applications use toaccomplish a task. They appear in all facets of application developmentfrom the smallest system utility to large enterprise services. Theirvalue is so apparent that more [...]]]></description>
			<content:encoded><![CDATA[<h2><span class="smallblack">3.0. Introduction</span></h2>
<p><span class="smallblack">It would be very rare to create an entireapplication without using a single string. Strings help make sense ofthe seemingly random jumble of binary data that applications use toaccomplish a task. They appear in all facets of application developmentfrom the smallest system utility to large enterprise services. Theirvalue is so apparent that more and more connected systems are leaningtoward string data within their communication protocols by utilizingthe Extensible Markup Language (XML) rather than the more cumbersometraditional transmission of large binary data. This book uses stringsextensively to examine the internal contents of variables and theresults of program flow using Framework Class Libraries (FCL) methodssuch as <tt>Console.WriteLine</tt> and <tt>MessageBox.Show</tt>.</span></p>
<p><span class="smallblack">In this chapter, you will learn how to takeadvantage of the rich support for strings within the .NET Framework andthe C# language. Coverage includes ways to manipulate string contents,programmatically inspect strings and their character attributes, andoptimize performance when working with string objects. Furthermore,this chapter uncovers the power of regular expressions and how theyallow you to effectively parse and manipulate string data. Afterreading this chapter, you will be able to use regular expressions in avariety of different situations where their value is apparent.</span></p>
<p><span class="smallblack"><a name="Heading3"></a></span></p>
<h2><span class="smallblack">3.1. Creating and Using String Objects</span></h2>
<p><span class="smallblack"><b>You want to create and manipulate string data within your application.</b></span></p>
<p><span class="smallblack"><a name="Heading4"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">The C# language, knowing the importance of string data, contains a <tt>string</tt> keyword that simulates the behavior of a value data type. To create a string, declare a variable using the <tt>string</tt>keyword. You can use the assignment operator to initialize the variableusing a static string or with an already initialized string variable.</span></p>
<p><span class="smallblack">string string1 = &quot;This is a string&quot;;<br />string string2 = string1;</span>
<p><span class="smallblack">To gain more control over string initialization, declare a variable using the <tt>System.String</tt> data type and create a new instance using the <tt>new</tt><i> </i>keyword. The <tt>System.String</tt>class contains several constructors that you can use to initialize thestring value. For instance, to create a new string that is a smallsubset of an existing string, use the overloaded constructor, whichtakes a character array and two integers denoting the beginning indexand the number of characters from that index to copy:</span></p>
<p><span class="smallblack">class Class1<br />{<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string string1 = &quot;Field1, Field2&quot;;<br /> System.String string2 = new System.String( string1.ToCharArray(), 8, 6 );</p>
<p> Console.WriteLine( string2 );</p>
<p> }<br />}</span>
<p><span class="smallblack">Finally, if you know a string will be intensively manipulated, use the <tt>System.Text. StringBuilder</tt> class. Creating a variable of this data type is similar to using the <tt>System.String</tt>class, and it contains several constructors to initialize the internalstring value. The key internal difference between a regular stringobject and a <tt>StringBuilder</tt><i> </i>lies in performance.Whenever a string is manipulated in some manner, a new object has to becreated, which subsequently causes the old object to be marked fordeletion by the garbage collector. For a string that undergoes severaltransformations, the performance hit associated with frequent objectcreation and deletions can be great. The <tt>StringBuilder</tt><i> </i>class,on the other hand, maintains an internal buffer, which expands to makeroom for more string data should the need arise, thereby decreasingfrequent object activations.</span></p>
<p><span class="smallblack"><a name="Heading5"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">There is no recommendation on whether you use the <tt>string</tt> keyword or the <tt>System.String</tt> class. The <tt>string</tt><i> </i>keyword is simply an alias for this class, so it is all a matter of taste. We prefer using the <tt>string</tt> keyword, but this preference is purely aesthetic. For this reason, we simply refer to the <tt>System.String</tt> class as the <tt>string</tt> class or data type.</span></p>
<p><span class="smallblack">The <tt>string</tt> class contains manymethods, both instance and static, for manipulating strings. If youwant to compare strings, you can use the <tt>Compare</tt> method. If you are just testing for equality, then you might want to use the overloaded equality operator (<tt>==</tt>). However, the <tt>Compare</tt>method returns an integer instead of Boolean value denoting how the twostrings differ. If the return value is 0, then the strings are equal.If the return value is greater than 0, as shown in Listing 3.1, thenthe first operand is greater alphabetically than the second operand. Ifthe return value is less than 0, the opposite is true. When a string issaid to be alphabetically greater or lower than another, each characterreading from left to right from both strings is compared using itsequivalent ASCII value. </span></p>
<h4><span class="smallblack"> Listing 3.1 Using the Compare Method in the <tt>String</tt> Class </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _1_UsingStrings<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string string1 = &quot;&quot;;<br /> String string2 = &quot;&quot;;</p>
<p> Console.Write( &quot;Enter string 1: &quot; );<br /> string1 = Console.ReadLine();<br /> Console.Write( &quot;Enter string 2: &quot; );<br /> string2 = Console.ReadLine();</p>
<p> // string and String are the same types<br /> Console.WriteLine( &quot;string1 is a {0}\nstring2 is a {1}&quot;, <br /> string1.GetType().FullName, string2.GetType().FullName );</p>
<p> CompareStrings( string1, string2 );<br /> }</p>
<p> public static void CompareStrings( string str1, string str2 )<br /> {<br /> int compare = String.Compare( str1, str2 );</p>
<p> if( compare == 0 )<br /> {<br /> Console.WriteLine( &quot;The strings {0} and {1} are the same.\n&quot;,<br /> str1, str2 );<br /> }<br /> else if( compare &lt; 0 )<br /> {<br /> Console.WriteLine( &quot;The string {0} is less than {1}&quot;,<br /> str1, str2 );<br /> }<br /> else if( compare &gt; 0 )<br /> {<br /> Console.WriteLine( &quot;The string {0} is greater than {1}&quot;,<br /> str1, str2 );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack">As mentioned earlier, the <tt>string</tt>class contains both instance and static methods. Sometimes you have nochoice about whether to use an instance or static method. However, afew of the instance methods contain a static version as well. Becausecalling a static method is a nonvirtual function call, you seeperformance gains if you use this version. An example where you mightsee both instance and static versions appears in Listing 3.1. Thestring comparison uses the static <tt>Compare</tt> method. You can also do so using the nonstatic <tt>CompareTo</tt>method using one of the string instances passed in as parameters. Inmost cases, the performance gain is negligible, but if an applicationneeds to repeatedly call these methods, you might want to considerusing the static over the non-static method.</span></p>
<p><span class="smallblack">The <tt>string</tt> class is immutable. Once a string is created, it cannot be manipulated. Methods within the <tt>string</tt>class that modify the original string instance actually destroy thestring and create a new string object rather than manipulate theoriginal string instance. It can be exp</p>
<p>ensive t<br />
o repeatedly call <tt>string</tt> methods if new objects are created and destroyed continuously. To solve this, the .NET Framework contains a <tt>StringBuilder</tt> class contained within the <tt>System.Text</tt> namespace, which is explained later in this chapter.</span></p>
<p><span class="smallblack"><a name="Heading6"></a></span></p>
<h2><span class="smallblack">3.2. Formatting Strings</span></h2>
<p><span class="smallblack"><b>Given one or more objects, you want to create a single formatted string representation.</b></span></p>
<p><span class="smallblack"><a name="Heading7"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">You can format strings using numeric and picture formatting within <tt>String.Format</tt> or within any method that uses string-formatting techniques for parameters such as <tt>Console.WriteLine</tt>.</span></p>
<p><span class="smallblack"><a name="Heading8"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">The <tt>String</tt> class as well as a fewother methods within the .NET Framework allow you to format strings topresent them in a more ordered and readable format. Up to this point inthe book, we used basic formatting when calling the <tt>Console.WriteLine</tt> method. The first parameter to <tt>Console.WriteLine</tt>is the format specifier string. This string controls how the remainingparameters to the method should appear when displayed. You useplaceholders within the format string to insert the value of avariable. This placeholder uses the syntax <tt>{</tt>n<tt>}</tt> where n is the index in the parameter list following the format specifier. Take the following line of code, for instance:</span></p>
<p><span class="smallblack">Console.WriteLine( &quot;x={0}, y={1}, {0}+{1}={2}&quot;, x, y, x+y );</span>
<p><span class="smallblack">This line of code has three parametersfollowing the format specifier string. You use placeholders within theformat specification, and when this method is called, the appropriatesubstitutions are made. Although you can do the same thing using stringconcatenation, the resultant line of code is slightly obfuscated:</span></p>
<p><span class="smallblack">string s = &quot;x=&quot; + x + &quot;,y=&quot; + y + &quot;, &quot; + x + &quot;+&quot; + y + &quot;=&quot; + (x+y);<br />Console.WriteLine( s );</span>
<p><span class="smallblack">You can further refine the format byapplying format attributes on the placeholders themselves. Theseadditional attributes follow the parameter index value and areseparated from that index with a <tt>:</tt> character. There are twotypes of special formatting available. The first is numeric formatting,which lets you format a numeric parameter into one of nine differentnumeric formats, as shown in Table 3.1. The format of these specifiers,using the currency format as an example, is <tt>C</tt>xx<i> </i>where xx<i> </i>is a number from 1 to 99 specifying the number of digits to display.<i> </i>Listing3.2 shows how to display an array of integers in hexadecimal format,including how to specify the number of digits to display. Notice alsohow you can change the case of the hexadecimal numbers A through F byusing an uppercase or lowercase format specifier.</span></p>
<h4><span class="smallblack"> Table 3.1 Numeric Formatting Specifiers</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="68"></col>
<col width="139"></col>
<col width="234"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b>Character</b></p>
</td>
<td valign="TOP">
<p><b>Format</b></p>
</td>
<td valign="TOP">
<p><b>Description</b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>C</tt> or <tt>c</tt></p>
</td>
<td valign="TOP">
<p>Currency</p>
</td>
<td valign="TOP">
<p>Culturally aware currency format.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>D</tt> or <tt>d</tt></p>
</td>
<td valign="TOP">
<p>Decimal</p>
</td>
<td valign="TOP">
<p>Only supports integral numbers. Displays a string using decimal digits preceded by a minus sign if negative.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>E</tt> or <tt>e</tt></p>
</td>
<td valign="TOP">
<p>Exponential/scientific notation</p>
</td>
<td valign="TOP">
<p>Displays numbers in the form <tt>&plusmn;</tt>d<tt>.</tt>dddddd<tt>E&plusmn;</tt>dd where d is a decimal digit. </p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>F</tt> or <tt>f</tt></p>
</td>
<td valign="TOP">
<p>Fixed point</p>
</td>
<td valign="TOP">
<p>Displays a series of decimal digits with a decimal point and additional digits.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>G</tt> or <tt>g</tt></p>
</td>
<td valign="TOP">
<p>General format</p>
</td>
<td valign="TOP">
<p>Displays either as a fixed-point or scientific notation based on the size of the number.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>N</tt> or <tt>n</tt></p>
</td>
<td valign="TOP">
<p>Number format</p>
</td>
<td valign="TOP">
<p>Similar to fixed point but uses a separator character (such as <tt>,</tt>) for groups of digits.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>P</tt> or <tt>p</tt></p>
</td>
<td valign="TOP">
<p>Percentage</p>
</td>
<td valign="TOP">
<p>Multiplies the number by 100 and displays with a percent symbol.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>R</tt> or <tt>r</tt></p>
</td>
<td valign="TOP">
<p>Roundtrip</p>
</td>
<td valign="TOP">
<p>Formats a floating-point number so that it can be successfully converted back to its original value.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>X</tt> or <tt>x</tt></p>
</td>
<td valign="TOP">
<p>Hexadecimal</p>
</td>
<td valign="TOP">
<p>Displays an integral number using the base-16 number system.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<h4><span class="smallblack"> Listing 3.2 Specifying a Different Numeric Format by Adding Format Specifiers on a Parameter Placeholder </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _2_Formatting<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> double[] numArray = {2, 5, 4.5, 45.43, 200000};</p>
<p> // format in lowercase hex<br /> Console.WriteLine( &quot;\n\nHex (lower)\n&#8212;&#8212;&#8212;&#8211;&quot; );<br /> foreach( double num in numArray )<br /> {<br /> Console.Write( &quot;0x{0:x}\t&quot;, (int) num );<br /> }</p>
<p> // format in uppercase hex<br /> Console.WriteLine( &quot;\n\nHex (upper)\n&#8212;&#8212;&#8212;&#8211;&quot; );<br /> foreach( double num in numArray )<br /> {<br /> Console.Write( &quot;0x{0:X}\t&quot;, (int) num );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack">Another type of formatting is <i>picture</i>formatting. Picture formatting allows you to create a custom formatspecifier using various symbols within the format specifier string.Table 3.2 lists the available picture format characters. Listing 3.3also shows how to create a custom format specifier. In that code, thedigits of the input number are extracted and displayed using acombination of digit placeholders and a decimal-point specifier.Furthermore, you can see that you are free to add characters not listedin the table. This freedom allows you to add literal charactersintermixed with the digits.</span></p>
<h4><span class="smallblack"> Table 3.2 Picture Formatting Specifiers</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="60"></col>
<col width="144"></col>
<col width="238"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Character</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Name</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>0</tt></p>
</td>
<td valign="TOP">
<p>Zero placeholder</p>
</td>
<td valign="TOP">
<p>Copies a digit to the result string if a digit is at the position of the <tt>0</tt>. If no digit is present, a 0 is displayed.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>#</tt></p>
</td>
<td valign="TOP">
<p>Display digit placeholder</p>
</td>
<td valign="TOP">
<p>Copies a digit to the result string if a digit appears at the position of the <tt>#</tt>. If no digit is present, nothing is displayed.</p>
</td>
</tr</p>
<p>><br />
<tr valign="TOP">
<td valign="TOP">
<p><tt>.</tt></p>
</td>
<td valign="TOP">
<p>Decimal point</p>
</td>
<td valign="TOP">
<p>Represents the location of the decimal point in the resultant string.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>,</tt></p>
</td>
<td valign="TOP">
<p>Group separator and number scaling</p>
</td>
<td valign="TOP">
<p>Inserts thousands separators if placed between two placeholders or scales a number down by 1,000 per <tt>,</tt> character when placed directly to the left of a decimal point.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>&amp;</tt></p>
</td>
<td valign="TOP">
<p>Percent</p>
</td>
<td valign="TOP">
<p>Multiplies a number by 100 and inserts a <tt>%</tt> symbol.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>E&plusmn;0</tt>, <tt>e&plusmn;0</tt></p>
</td>
<td valign="TOP">
<p>Exponential notation</p>
</td>
<td valign="TOP">
<p>Displays the number in exponential notation using the number of 0s as a placeholder for the exponent value.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\</tt></p>
</td>
<td valign="TOP">
<p>Escape character</p>
</td>
<td valign="TOP">
<p>Used to specify a special escape-character formatting instruction. Some of these include <tt>\n</tt> for newline, <tt>\t</tt> for tab, and <tt>\</tt> for the <tt>\</tt> character.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>;</tt></p>
</td>
<td valign="TOP">
<p>Section separator</p>
</td>
<td valign="TOP">
<p>Separates positive, negative, and zero numbers in the format stringin which you can apply different formatting rules based on the sign ofthe original number.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Listing 3.3 shows how custom formatting can separate a number by its decimal point. Using a <tt>foreach</tt><i> </i>loop,each value is printed using three different formats. The first formatwill output the value&#39;s integer portion using the following formatstring:</span></p>
<p><span class="smallblack">0:$#,#</span>
<p><span class="smallblack">Next, the decimal portion is written. Ifthe value does not explicitly define a decimal portion, zeroes arewritten instead. The format string to output the decimal value is</span></p>
<p><span class="smallblack">$.#0;</span>
<p><span class="smallblack">Finally, the entire value is displayed up to two decimal places using the following format string:</span></p>
<p><span class="smallblack">{0:$#,#.00}</span><br />
<h4><span class="smallblack"> Listing 3.3 Using Picture Format Specifiers to Create Special Formats </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _2_Formatting<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> double[] numArray = {2, 5, 4.5, 45.43, 200000};</p>
<p> // format as custom<br /> Console.WriteLine( &quot;\n\nCustom\n&#8212;&#8212;&quot; );<br /> foreach( double num in numArray )<br /> {<br /> Console.WriteLine( &quot;{0:$#,# + $.#0;} = {0:$#,#.00}&quot;, num );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading9"></a></span></p>
<h2><span class="smallblack">3.3. Accessing Individual String Characters</span></h2>
<p><span class="smallblack"><b>You want to process individual characters within a string.</b></span></p>
<p><span class="smallblack"><a name="Heading10"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the index operator (<tt>[]</tt>) byspecifying the zero-based index of the character within the string thatyou want to extract. Furthermore, you can also use the <tt>foreach</tt> enumerator on the string using a <tt>char</tt> structure as the enumeration data type.</span></p>
<p><span class="smallblack"><a name="Heading11"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">The <tt>string</tt> class is really acollection of objects. These objects are individual characters. You canaccess each character using the same methods you would use to access anobject in most other collections (which is covered in the next chapter).</span></p>
<p><span class="smallblack">You use an indexer to specify which objectin a collection you want to retrieve. In C#, the first object begins atthe 0 index of the string. The objects are individual characters whosedata type is <tt>System.Char</tt>, which is aliased with the <tt>char</tt> keyword. The indexer for the <tt>string</tt>class, however, can only access a character and cannot set the value ofa character at that position. Because a string is immutable, you cannotchange the internal array of characters unless you create and return anew string. If you need the ability to index a string to set individualcharacters, use a <tt>StringBuilder</tt> object.</span></p>
<p><span class="smallblack">Listing 3.4 shows how to access thecharacters in a string. One thing to point out is that because thestring also implements the <tt>IEnumerable</tt><i> </i>interface, you can use the <tt>foreach</tt> control structure to enumerate through the string.</span></p>
<h4><span class="smallblack">Listing 3.4<b> Accessing Characters Using Indexers and Enumeration </b></span></h4>
<p><span class="smallblack">using System;<br />using System.Text;</p>
<p>namespace _3_Characters<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string str = &quot;abcdefghijklmnopqrstuvwxyz&quot;;</p>
<p> str = ReverseString( str );<br /> Console.WriteLine( str );</p>
<p> str = ReverseStringEnum( str );<br /> Console.WriteLine( str );<br /> }</p>
<p> static string ReverseString( string strIn )<br /> {<br /> StringBuilder sb = new StringBuilder(strIn.Length);</p>
<p> for( int i = 0; i &lt; strIn.Length; ++i )<br /> {<br /> sb.Append( strIn[(strIn.Length-1)-i] );<br /> }<br /> return sb.ToString();<br /> }</p>
<p> static string ReverseStringEnum( string strIn )<br /> {<br /> StringBuilder sb = new StringBuilder( strIn.Length );<br /> foreach( char ch in strIn )<br /> {<br /> sb.Insert( 0, ch );<br /> }</p>
<p> return sb.ToString();<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading12"></a></span></p>
<h2><span class="smallblack">3.4. Analyzing Character Attributes</span></h2>
<p><span class="smallblack"><b>You want to evaluate the individual characters in a string to determine a character&#39;s attributes.</b></span></p>
<p><span class="smallblack"><a name="Heading13"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">The <tt>System.Char</tt> structure containsseveral static functions that let you test individual characters. Youcan test whether a character is a digit, letter, or punctuation symbolor whether the character is lowercase or uppercase.</span></p>
<p><span class="smallblack"><a name="Heading14"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">One of the hardest issues to handle whenwriting software is making sure users input valid data. You can usemany different methods, such as restricting input to only digits, butultimately, you always need an underlying validating test of the inputdata. </span></p>
<p><span class="smallblack">You can use the <tt>System.Char</tt><i> </i>structure to perform a variety of text-validation procedures. Listing 3.5 demonstrates validating user input as well as inspecting the characteristics of a character. It begins by displaying a menu and then waiting for user input using the <tt>Console.ReadLine</tt><i> </i>method. Once a user enters a command, you make a check using the method <tt>ValidateMainMenuInput</tt>. This method checks to make sure the first character in the input string is not a digit or punctuation symbol. If the validation passes, the string is passed to a method that inspects each character in the input string. This method simply enumerates through all the characters in the input string and prints descriptive messages based on the characteristics. Some of the <tt>System.Char</tt> methods for inspection have been inadvertently left out of Listing 3.5. Table 3.3 shows the remaining methods and their functionality. The results of runnin</p>
<p>g the application in Listing 3.5 appear in <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig01.jpg">Figure 3.1</a>.</span></p>
<h4><span class="smallblack"> Listing 3.5 Using the Static Methods in <tt>System.Char</tt> to Inspect the Details of a Single Character</span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _4_CharAttributes<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> char cmd = &#39;x&#39;;</p>
<p> string input;<br /> do<br /> {<br /> DisplayMainMenu();<br /> input = Console.ReadLine();</p>
<p> if( (input == &quot;&quot; ) || <br /> ValidateMainMenuInput( Char.ToUpper(input[0]) ) == 0 )<br /> {<br /> Console.WriteLine( &quot;Invalid command!&quot; );<br /> }<br /> else<br /> {<br /> cmd = Char.ToUpper(input[0]);</p>
<p> switch( cmd )<br /> {<br /> case &#39;Q&#39;:<br /> {<br /> break;<br /> }</p>
<p> case &#39;N&#39;:<br /> {<br /> Console.Write( &quot;Enter a phrase to inspect: &quot; );<br /> input = Console.ReadLine();<br /> InspectPhrase( input );<br /> break;<br /> }<br /> }<br /> }<br /> } while ( cmd != &#39;Q&#39; );<br /> }</p>
<p> private static void InspectPhrase( string input )<br /> {<br /> foreach( char ch in input )<br /> {<br /> Console.Write( ch + &quot; &#8211; &quot;);</p>
<p> if( Char.IsDigit(ch) )<br /> Console.Write( &quot;IsDigit &quot; );<br /> if( Char.IsLetter(ch) )<br /> {<br /> Console.Write( &quot;IsLetter &quot; );<br /> Console.Write( &quot;(lowercase={0}, uppercase={1})&quot;, <br /> Char.ToLower(ch), Char.ToUpper(ch));<br /> }<br /> if( Char.IsPunctuation(ch) )<br /> Console.Write( &quot;IsPunctuation &quot; );<br /> if( Char.IsWhiteSpace(ch) )<br /> Console.Write( &quot;IsWhitespace&quot; );</p>
<p> Console.Write(&quot;\n&quot;);</p>
<p> }<br /> }<br /> private static int ValidateMainMenuInput( char input )<br /> {<br /> // a simple check to see if input == &#39;N&#39; or &#39;Q&#39; is good enough<br /> // the following is for illustrative purposes<br /> if( Char.IsDigit( input ) == true )<br /> return 0;<br /> else if ( Char.IsPunctuation( input ) )<br /> return 0;<br /> else if( Char.IsSymbol( input ))<br /> return 0;<br /> else if( input != &#39;N&#39; &amp;&amp; input != &#39;Q&#39; )<br /> return 0;</p>
<p> return (int) input;<br /> }</p>
<p> private static void DisplayMainMenu()<br /> {<br /> Console.WriteLine( &quot;\nPhrase Inspector\n&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-&quot; );<br /> Console.WriteLine( &quot;N)ew Phrase&quot; );<br /> Console.WriteLine( &quot;Q)uit\n&quot; );<br /> Console.Write( &quot;&gt;&gt; &quot; );<br /> }<br /> }<br />}</span><br />
<h4><span class="smallblack"> Table 3.3 <tt>System.Char</tt> Inspection Methods</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="113"></col>
<col width="329"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><tt>Name</tt></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsControl</tt></p>
</td>
<td valign="TOP">
<p>Denotes a control character such as a tab or carriage return.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsDigit</tt></p>
</td>
<td valign="TOP">
<p>Indicates a single decimal digit.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsLetter</tt></p>
</td>
<td valign="TOP">
<p>Used for alphabetic characters.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsLetterOrDigit</tt></p>
</td>
<td valign="TOP">
<p>Returns <tt>true</tt> if the character is a letter or a digit.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsLower</tt></p>
</td>
<td valign="TOP">
<p>Used to determine whether a character is lowercase.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsNumber</tt></p>
</td>
<td valign="TOP">
<p>Tests whether a character is a valid number.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsPunctuation</tt></p>
</td>
<td valign="TOP">
<p>Denotes whether a character is a punctuation symbol.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsSeparator</tt></p>
</td>
<td valign="TOP">
<p>Denotes a character used to separate strings. An example is the space character.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsSurrogate</tt></p>
</td>
<td valign="TOP">
<p>Checks for a Unicode surrogate pair, which consists of two 16-bit values primarily used in localization contexts.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsSymbol</tt></p>
</td>
<td valign="TOP">
<p>Used for symbolic characters such as <tt>$</tt> or <tt>#</tt>.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsUpper</tt></p>
</td>
<td valign="TOP">
<p>Used to determine whether a character is uppercase.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>IsWhiteSpace</tt></p>
</td>
<td valign="TOP">
<p>Indicates a character classified as whitespace such as a space character, tab, or carriage return.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack"><a href="http://www.csharphelp.com/archives3/files/archive561/03Fig01.jpg"><b>Figure 3.1</b></a><br />Use the <tt>static</tt> method in the <tt>System.Char</tt> class to inspect character attributes.</span></p>
<p><span class="smallblack">The <tt>System.Char</tt> structure isdesigned to work with a single Unicode character. Because a Unicodecharacter is 2 bytes, the range of a character is from 0 to 0xFFFF. Forportability reasons in future systems, you can always check the size ofa <tt>char</tt> by using the <tt>MaxValue</tt> constant declared in the <tt>System.Char</tt><i> </i>structure. One thing to keep in mind when working with characters is to avoid the confusion of mixing <tt>char</tt>types with integer types. Characters have an ordinal value, which is aninteger value used as a lookup into a table of symbols. One example ofa table is the ASCII table, which contains 255 characters and includesthe digits 0 through 9, letters, punctuation symbols, and formattingcharacters. The confusion lies in the fact that the number 6, forinstance, has an ordinal <tt>char</tt> value of 0&#215;36. Therefore, the line of code meant to initialize a character to the number 6</span></p>
<p><span class="smallblack">char ch = (char) 6;</span>
<p><span class="smallblack">is wrong because the actual character inthis instance is ^F, the ACK control character used in modemhandshaking protocols. Displaying this value in the console would notprovide the 6 that you were looking for. You could have chosen twodifferent methods to initialize the variable. The first way is</span></p>
<p><span class="smallblack">char ch = (char) 0&#215;36;</span>
<p><span class="smallblack">which produces the desired result and prints the number 6 to the console if passed to the <tt>Console.Write</tt> method. However, unless you have the ASCII table memorized, this procedure can be cumbersome. To initialize a <tt>char</tt><i> </i>variable, simply place the value between single quotes: </span></p>
<p><span class="smallblack">char ch = &#39;6&#39;;</span>
<p><span class="smallblack"><a name="Heading15"></a></span></p>
<h2><span class="smallblack">3.5. Case-Insensitive String Comparison</span></h2>
<p><span class="smallblack"><b>You want to perform case-insensitive string comparison on two strings.</b></span></p>
<p><span class="smallblack"><a name="Heading16"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the overloaded <tt>Compare</tt> method in the <tt>System.String</tt> class which accepts a Boolean value, <tt>ignoreCase</tt>, as the last parameter. This parameter specifies whether the comparison should be case insensitive (<tt>true</tt>) or case sensitive (<tt>false</tt>). To compare single characters, convert them to uppercase or lowercase, using <tt>ToUpper</tt><i> </i>or <tt>ToLower</tt>, and then perform the comparison.</span></p>
<p><span class="smallblack"><a name="Heading17"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Validating user input requires a lot offorethought into the possible values a user can enter. Making sure youcover the range of possible values can be a daunting task, and you</p>
<p>might ultimately run into human-computer interaction issues by severelylimiting what a user can enter. Case-sensitivity issues increase thepossible range of values, leading to greater security with respect tosuch things as passwords, but this security is usually at the expenseof a user&#39;s frustration when she forgets whether a character iscapitalized. As with many other programming problems, you must weighthe pros and cons.</span></p>
<p><span class="smallblack">To perform a case-insensitive comparison, you can use one of the many overloaded <tt>Compare</tt> methods within the <tt>System.String</tt>class. The methods that allow you to ignore case issues use a Booleanvalue as the last parameter in the method. This parameter is named <tt>ignoreCase</tt>, and when you set it to <tt>true</tt>, you make a case-insensitive comparison, as demonstrated in Listing 3.6.</span></p>
<h4><span class="smallblack"> Listing 3.6 Performing a Case-Insensitive String Comparison </span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _5_CaseComparison<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string str1 = &quot;This Is A String.&quot;;<br /> string str2 = &quot;This is a string.&quot;;</p>
<p> Console.WriteLine( &quot;Case sensitive comparison of&quot; +<br /> &quot; str1 and str2 = {0}&quot;, String.Compare( str1, str2 ));</p>
<p> Console.WriteLine( &quot;Case insensitive comparison of&quot; + <br /> &quot; str1 and str2 = {0}&quot;, String.Compare( str1, str2, true ));<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading18"></a></span></p>
<h2><span class="smallblack">3.6. Working with Substrings</span></h2>
<p><span class="smallblack"><b>You need to change or extract a specific portion of a string.</b></span></p>
<p><span class="smallblack"><a name="Heading19"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">To copy a portion of a string into a new string, use the <tt>SubString</tt> method within the <tt>System.String</tt><i> </i>class. You call this method using the string object instance of the source string:</span></p>
<p><span class="smallblack">string source = &quot;ABCD1234WXYZ&quot;;<br />string dest = source.Substring( 4, 4 );<br />Console.WriteLine( &quot;{0}\n&quot;, dest );</span>
<p><span class="smallblack">To copy a substring into an already existing character array, use the <tt>CopyTo</tt> method. To assign a character array to an existing string object, create a new instance of the string using the <tt>new</tt><i> </i>keyword, passing the character array as a parameter to the string constructor as shown in the following code, whose ouput appears in <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig02.jpg">Figure 3.2</a>:</span></p>
<p><span class="smallblack">string source = &quot;ABCD&quot;;<br />char [] dest = { &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39; };</p>
<p>Console.Write( &quot;Char array before = &quot; );<br />Console.WriteLine( dest );</p>
<p>// copy substring into char array<br />source.CopyTo( 0, dest, 4, source.Length );</p>
<p>Console.Write( &quot;Char array after = &quot; );<br />Console.WriteLine( dest );</p>
<p>// copy back into source string<br />source = new String( dest );</p>
<p>Console.WriteLine( &quot;New source = {0}\n&quot;, source ); </span>
<p><span class="smallblack"> <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig02.jpg"><b>Figure 3.2 </b></a><br /> Use the <tt>CopyTo</tt> method to copy a substring into an existing character array.</span></p>
<p><span class="smallblack">If you need to remove a substring within a string and replace it with a different substring, use the <tt>Replace</tt><i> </i>method. This method accepts two parameters, the substring to replace and the string to replace it with:</span></p>
<p><span class="smallblack">string replaceStr = &quot;1234&quot;;<br />string dest = &quot;ABCDEFGHWXYZ&quot;;</p>
<p>dest = dest.Replace( &quot;EFGH&quot;, replaceStr );</p>
<p>Console.WriteLine( dest );</span>
<p><span class="smallblack">To extract an array of substrings that are separated from each other by one or more delimiters, use the <tt>Split</tt> method. This method uses a character array of delimiter characters and returns a string array of each substring within the original string as shown in the following code, whose output appears in <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig03.jpg">Figure 3.3</a>. You can optionally supply an integer specifying the maximum number of substrings to split:</span></p>
<p><span class="smallblack">char delim = &#39;\&#39;;<br />string filePath = &quot;C:\Windows\Temp&quot;;<br />string [] directories = null;</p>
<p>directories = filePath.Split( delim );</p>
<p>foreach (string directory in directories) <br />{<br /> Console.WriteLine(&quot;{0}&quot;, directory);<br />}</span>
<p><span class="smallblack"> <a href="http://www.csharphelp.com/archives3/files/archive561/03Fig03.jpg"><b>Figure 3.3 </b></a><br /> You can use the <tt>Split</tt> method in the <tt>System.String</tt> class to place delimited substrings into a string array.</span></p>
<p><span class="smallblack"><a name="Heading20"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Parsing strings is not for the faint ofheart. However, the job becomes easier if you have a rich set ofmethods that allow you to perform all types of operations on strings.Substrings are the goal of a majority of these operations, and the <tt>string</tt> class within the .NET Framework contains many methods that are designed to extract or change just a portion of a string.</span></p>
<p><span class="smallblack">The <tt>Substring</tt><i> </i>methodextracts a portion of a string and places it into a new string object.You have two options with this method. If you pass a single integer,the <tt>Substring</tt><i> </i>method extracts the substring thatstarts at that index and continues until it reaches the end of thestring. One thing to keep in mind is that C# array indices are 0 based.The first character within the string will have an index of 0. Thesecond <tt>Substring</tt><i> </i>method accepts an additionalparameter that denotes the ending index. It lets you extract parts of astring in the middle of the string.</span></p>
<p><span class="smallblack">You can create a new character array from a string by using the <tt>ToCharArray</tt><i> </i>method of the <tt>string</tt> class. Furthermore, you can extract a substring from the string and place it into a character array by using the <tt>CopyTo</tt> method. The difference between these two methods is that the character array used with the <tt>CopyTo</tt> method must be an already instantiated array. Whereas the <tt>ToCharArray</tt><i> </i>returns a new character array, the <tt>CopyTo</tt>method expects an existing character array as a parameter to themethod. Furthermore, although methods exist to extract character arraysfrom a string, there is no instance method available to assign acharacter array to a string. To do this, you must create a new stringobject using the <tt>new</tt><i> </i>keyword, as opposed to creatingthe familiar value-type string, and pass the character array as aparameter to the string constructor.</span></p>
<p><span class="smallblack">Using the <tt>Replace</tt><i> </i>method isa powerful way to alter the contents of a string. This method allowsyou to search all instances of a specified substring within a stringand replace those with a different substring. Additionally, the lengthof the substring you want to replace does not have to be the samelength of the string you are replacing it with. If you recall thenumber of times you have performed a search and replace in anyapplication, you can see the possible advantages of this method.</span></p>
<p><span class="smallblack">One other powerful method is <tt>Split</tt>.By passing a character array consisting of delimiter characters, youcan split a string into a group of substrings and place them into astrin</p>
<p>g array. By passing an additional integer parameter, you can alsocontrol how many substrings to extract from the source string.Referring to the code example earlier demonstrating the <tt>Split</tt><i> </i>method, you can split a string representing a directory path into individual directory names by passing the <tt>\</tt>character as the delimiter. You are not, however, confined to using asingle delimiter. If you pass a character array consisting of severaldelimiters, the <tt>Split</tt><i> </i>method extracts substrings based on any of the delimiters that it encounters.</span></p>
<p><span class="smallblack"><a name="Heading21"></a></span></p>
<h2><span class="smallblack">3.7. Using Verbatim String Syntax</span></h2>
<p><span class="smallblack"><b>You want to represent a path to a file using a string without using escape characters for path separators.</b></span></p>
<p><span class="smallblack"><a name="Heading22"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">When assigning a literal string to a string object, preface the string with the <tt>@</tt> symbol. It turns off all escape-character processing so there is no need to escape path separators:</span></p>
<p><span class="smallblack">string nonVerbatim = &quot;C:\Windows\Temp&quot;;<br />string verbatim = @&quot;C:\Windows\Temp&quot;;</span>
<p><span class="smallblack"><a name="Heading23"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">A compiler error that happens so frequently comes from forgetting to escape path separators. Although a common programming <i>faux pas</i>is to include hard-coded path strings, you can overlook that rule whentesting an application. Visual C# .NET added verbatim string syntax asa feature to alleviate the frustration of having to escape all the pathseparators within a file path string, which can be especiallycumbersome for large paths.</span></p>
<p><span class="smallblack"><a name="Heading24"></a></span></p>
<h2><span class="smallblack">3.8. Choosing Between Constant and Mutable Strings</span></h2>
<p><span class="smallblack"><b>You want to choose the correct string data type to best fit your current application design.</b></span></p>
<p><span class="smallblack"><a name="Heading25"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">If you know a string&#39;s value will not change often, use a <tt>string</tt><i> </i>object,which is a constant value. If you need a mutable string, one that canchange its value without having to allocate a new object, use a <tt>StringBuilder</tt>.</span></p>
<p><span class="smallblack"><a name="Heading26"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Using a regular <tt>string</tt><i> </i>objectis best when you know the string will not change or will only changeslightly. This change includes the whole gamut of string operationsthat change the value of the object itself, such as concatenation,insertion, replacement, or removal of characters. The Common LanguageRuntime (CLR) can use certain properties of strings to optimizeperformance. If the CLR can determine that two string objects are thesame, it can share the memory that these string objects occupy. Thesestrings are then known as <i>interned</i> strings. The CLR contains anintern pool, which is a lookup table of string instances. Strings areautomatically interned if they are assigned to a literal string withincode. However, you can also manually place a string within the internpool by using the <tt>Intern</tt><i> </i>method. To test whether a string is interned, use the <tt>IsInterned</tt> method, as shown in Listing 3.7.</span></p>
<h4><span class="smallblack"> Listing 3.7 Interning a String by Using the <tt>Intern</tt> Method</span></h4>
<p><span class="smallblack">using System;</p>
<p>namespace _7_StringBuilder<br />{<br /> /// &lt;summary&gt;<br /> /// Summary description for Class1.<br /> /// &lt;/summary&gt;<br /> class Class1<br /> {<br /> /// &lt;summary&gt;<br /> /// The main entry point for the application.<br /> /// &lt;/summary&gt;<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string sLiteral = &quot;Automatically Interned&quot;;<br /> string sNotInterned = &quot;Not &quot; + sLiteral;</p>
<p> TestInterned( sLiteral );<br /> TestInterned( sNotInterned );</p>
<p> String.Intern( sNotInterned );<br /> TestInterned( sNotInterned );<br /> }</p>
<p> static void TestInterned( string str )<br /> {<br /> if( String.IsInterned( str ) != null )<br /> {<br /> Console.WriteLine( &quot;The string \&quot;{0}\&quot; is interned.&quot;, str );<br /> }<br /> else<br /> {<br /> Console.WriteLine( &quot;The string \&quot;{0}\&quot; is not interned.&quot;, str );<br /> }<br /> }<br /> }<br />}</span>
<p><span class="smallblack">A <tt>StringBuilder</tt> behaves similarlyto a regular string object and also contains similar method calls.However, there are no static methods because the <tt>StringBuilder</tt> class is designed to work on string instances. Method calls on an instance of a <tt>StringBuilder</tt><i> </i>object change the internal string of that object, as shown in Listing 3.8. A <tt>StringBuilder</tt>maintains its mutable appearance by creating a buffer that is largeenough to contain a string value and additional memory should thestring need to grow. </span></p>
<h4><span class="smallblack"> Listing 3.8 Manipulating an Internal String Buffer Instead of Returning New String Objects </span></h4>
<p><span class="smallblack">using System;<br />using System.Text;</p>
<p>namespace _7_StringBuilder<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> string string1 = &quot;&quot;;<br /> String string2 = &quot;&quot;;</p>
<p> Console.Write( &quot;Enter string 1: &quot; );<br /> string1 = Console.ReadLine();<br /> Console.Write( &quot;Enter string 2: &quot; );<br /> string2 = Console.ReadLine();</p>
<p> BuildStrings( string1, string2 );<br /> }</p>
<p> public static void BuildStrings( string str1, string str2 )<br /> {<br /> StringBuilder sb = new StringBuilder( str1 + str2 );<br /> sb.Insert( str1.Length, &quot; is the first string.\n&quot; );<br /> sb.Insert( sb.Length, &quot; is the second string.\n&quot; );</p>
<p> Console.WriteLine( sb );<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading27"></a></span></p>
<h2><span class="smallblack">3.9. Optimizing <tt>StringBuilder</tt> Performance</span></h2>
<p><span class="smallblack"><b>Knowing that a </b><tt>StringBuilder</tt><b> object can suffer more of a performance hit than a regular string object, you want to optimize the </b><tt>StringBuilder</tt><b> object to minimize performance issues.</b></span></p>
<p><span class="smallblack"><a name="Heading28"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the <tt>EnsureCapacity</tt><i> </i>method in the <tt>StringBuilder</tt><i> </i>class. Set this integral value to a value that signifies the length of the longest string you may store in this buffer.</span></p>
<p><span class="smallblack"><a name="Heading29"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">The <tt>StringBuilder</tt><i> </i>classcontains methods that allow you to expand the memory of the internalbuffer based on the size of the string you may store. As your stringcontinually grows, the <tt>StringBuilder</tt><i> </i>won&#39;t have torepeatedly allocate new memory for the internal buffer. In other words,if you attempt to place a larger length string than what the internalbuffer of the <tt>StringBuilder</tt> class can accept, then the classwill have to allocate additional memory to accept the new data. If youcontinuously add strings that increase in size from the last inputstring, the <tt>StringBuilder</tt><i> </i>class will have to allocate a new buffer size, which it does internally by calling the <tt>GetStringForStringBuilder</tt> method defined in the <tt>System.String</tt> class. This method ultimately calls the unmanaged method <tt>FastAllocateStrin</p>
<p>g</tt>. By giving the <tt>StringBuilder</tt><i> </i>class a hint using the <tt>EnsureCapacity</tt><i> </i>method, you can help alleviate some of this continual memory reallocation, thereby optimizing the <tt>StringBuilder</tt><i> </i>performance by reducing the amount of memory allocations needed to store a string value.</span></p>
<p><span class="smallblack"><a name="Heading30"></a></span></p>
<h2><span class="smallblack">3.10. Understanding Basic Regular Expression Syntax</span></h2>
<p><span class="smallblack"><b>You want to create a regular expression.</b></span></p>
<p><span class="smallblack"><a name="Heading31"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Regular expressions consist of a series ofcharacters and quantifiers on those characters. The charactersthemselves can be literal or can be denoted by using character classes,such as <tt>\d</tt>, which denotes a digit character class, or <tt>\S</tt>, which denotes any nonwhitespace character. </span></p>
<h4><span class="smallblack"> Table 3.4 Regular Expression Single Character Classes</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="54"></col>
<col width="198"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Class</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\d</tt></p>
</td>
<td valign="TOP">
<p>Any digit</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\D</tt></p>
</td>
<td valign="TOP">
<p>Any nondigit</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\w</tt>s</p>
</td>
<td valign="TOP">
<p>Any word character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\W</tt></p>
</td>
<td valign="TOP">
<p>Any nonword character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\s</tt></p>
</td>
<td valign="TOP">
<p>Any whitespace character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\SW</tt></p>
</td>
<td valign="TOP">
<p>Any nonwhitespace</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Inaddition to the single character classes, you can also specify a rangeor set of characters using ranged and set character classes. Thisability allows you to narrow the search for a specified character bylimiting characters within a specified range or within a defined set.</span></p>
<h4><span class="smallblack"> Table 3.5 Ranged and Set Character Classes</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="108"></col>
<col width="334"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Format</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>.</tt></p>
</td>
<td valign="TOP">
<p>Any character except newline.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\p{</tt>uc<tt>}</tt></p>
</td>
<td valign="TOP">
<p>Any character within the Unicode character category uc.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>[abcxyz]</tt></p>
</td>
<td valign="TOP">
<p>Any literal character in the set.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\P{uc}</tt></p>
</td>
<td valign="TOP">
<p>Any character not within the Unicode character category uc.</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>[^abcxyz]</tt></p>
</td>
<td valign="TOP">
<p>Any character not in the set of literal characters.</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Quantifierswork on character classes to expand the number of characters thecharacter classes should match. You need to specify, for instance, awildcard character on a character class, which means 0 or morecharacters within that class. Additionally, you can also specify a setnumber of matches of a class that should occur by using an integerwithin braces following the character class designation.</span></p>
<h4><span class="smallblack"> Table 3.6 Character Class Quantifiers</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="68"></col>
<col width="189"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Format</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>*</tt></p>
</td>
<td valign="TOP">
<p>0 or more characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>+</tt></p>
</td>
<td valign="TOP">
<p>1 or more characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>?</tt></p>
</td>
<td valign="TOP">
<p>0 or 1 characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>{</tt>n<tt>}</tt></p>
</td>
<td valign="TOP">
<p>Exactly n<i> </i>characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>{</tt>n,<tt>}</tt></p>
</td>
<td valign="TOP">
<p>At least n<i> </i>characters</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>{</tt>n,m<tt>}</tt></p>
</td>
<td valign="TOP">
<p>At least n<i> </i>but no more than m<i> </i>characters</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack">Youcan also specify where a certain regular expression should start withina string. Positional assertions allow you to, for instance, match acertain expression as long as it occurs at the beginning or ending of astring. Furthermore, you can create a regular expression that operateson a set of words within a string by using a positional assertion thatcontinues matching on each subsequent word separated by anynonalphanumeric character.</span></p>
<h4><span class="smallblack"> Table 3.7 Positional (Atomic Zero-Width) Assertions</span></h4>
<table border="2" cellpadding="2" cellspacing="2">
<colgroup>
<col width="63"></col>
<col width="378"></col>
</colgroup>
<tbody>
<tr valign="TOP">
<td valign="TOP">
<p><b><b>Format</b></b></p>
</td>
<td valign="TOP">
<p><b><b>Description</b></b></p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>^</tt></p>
</td>
<td valign="TOP">
<p>Beginning of a string or beginning of a newline</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\z</tt></p>
</td>
<td valign="TOP">
<p>End of the string, including the newline character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>$</tt></p>
</td>
<td valign="TOP">
<p>End of a string before a newline character or at the end of the line</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\G</tt></p>
</td>
<td valign="TOP">
<p>Continues where the last match left off</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\A</tt></p>
</td>
<td valign="TOP">
<p>Beginning of a string</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\b</tt></p>
</td>
<td valign="TOP">
<p>Between word boundaries (between alphanumeric and nonalphanumeric characters)</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\Z</tt></p>
</td>
<td valign="TOP">
<p>End of the string before the newline character</p>
</td>
</tr>
<tr valign="TOP">
<td valign="TOP">
<p><tt>\B</tt></p>
</td>
<td valign="TOP">
<p>Characters not between word boundaries</p>
</td>
</tr>
</tbody>
</table>
<p><span class="smallblack"><br /><a name="Heading32"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Regular expressions use a variety ofcharacters both symbolic and literal to designate how a particularstring of text should be parsed. The act of parsing a string is knownas matching, and when applied to a regular expression, the match willbe either true or false. In other words, when you use a regularexpression to match a series of characters, the match will eithersucceed or fail. As you can see, this process has powerfulapplicability in the area of input validation.</span></p>
<p><span class="smallblack">You build regular expressions using aseries of character classes and quantifiers on those character classesas well as a few miscellaneous regular-expression constructs. You usecharacter classes to match a single character based either on what typeof character it is, such as a digit or letter, or whether it belongswithin a specified range or set of characters (as shown in Table 3.4).Using this information, you can create a series of character classes tomatch a certain string of text. For instance, if you want to specify<br />
aphone number using character classes, you can use the following regularexpression:</span></p>
<p><span class="smallblack">\(\d\d\d\)\s\d\d\d-\d\d\d\d</span>
<p><span class="smallblack">This expression begins by first escapingthe left parenthesis. You must escape it because parentheses are usedfor grouping expressions. Next you can see three digits representing aphone number&#39;s area code followed by the closing parenthesis. You use a<tt>\s</tt> to denote a whitespace character. The remainder of the regular expression contains the remaining digits of the phone number.</span></p>
<p><span class="smallblack">In addition to the single characterclasses, you can also use ranged and set character classes. They giveyou fine-grain control on exactly the type of characters the regularexpression should match. For instance, if you want to match anycharacter as long as it is a vowel, use the following expression:</span></p>
<p><span class="smallblack">[aeiou]</span>
<p><span class="smallblack">This line means that a character shouldmatch one of the literal characters within that set of characters. Aneven more specialized form of single character classes are Unicodecharacter categories. Unicode categories are similar to some of thecharacter-attribute inspection methods shown earlier in this chapter.For instance, you can use Unicode categories to match on uppercase orlowercase characters. Other categories include punctuation characters,currency symbols, and math symbols, to name a few. You can easily findthe full list of Unicode categories in MSDN under the topic &quot;UnicodeCategories Enumeration.&quot;</span></p>
<p><span class="smallblack">You can optimize the phone-number expression, although it&#39;s completely valid, by using <i>quantifiers</i>.Quantifiers specify additional information about the character,character class, or expression to which it applies. Some quantifiersinclude wildcards such as <tt>*</tt>, which means 0 or more occurrences, and <tt>?</tt>,which means only 0 or 1 occurrences of a pattern. You can also usebraces containing an integer to specify how many characters within agiven character class to match. Using this quantifier in thephone-number expression, you can specify that the phone number shouldcontain three digits for the area code followed by three digits andfour digits separated by a dash:</span></p>
<p><span class="smallblack">\(\d{3}\)\s\d{3}-\d{4}</span>
<p><span class="smallblack">Because the regular expression itself isn&#39;tthat complicated, you can still see that using quantifiers can simplifyregular-expression creation. In addition to character classes andquantifiers, you can also use positional information within a regularexpression. For instance, you can specify that given an input string,the regular expression should operate at the beginning of the string.You express it using the <tt>^</tt> character. Likewise, you can also denote the end of a string using the <tt>$</tt>symbol. Take note that this doesn&#39;t mean start at the end of the stringand attempt to make a match because that obviously seemscounterintuitive; no characters exist at the end of the string. Rather,by placing the <tt>$</tt> character following the rest of the regularexpression, it means to match the string with the regular expression aslong as the match occurs at the end of the string. For instance, if youwant to match a sentence in which a phone number is the last portion ofthe sentence, you could use the following:</span></p>
<p><span class="smallblack">\(\d{3}\)\s\d{3}-\d{4}$<br />My phone number is (555) 555-5555 = Match<br />(555) 555-5555 is my phone number = Not a match</span>
<p><span class="smallblack"><a name="Heading33"></a></span></p>
<h2><span class="smallblack">3.11. Validating User Input with Regular Expressions</span></h2>
<p><span class="smallblack"><b>You want to ensure valid user input by using regular expressions to test for validity.</b></span></p>
<p><span class="smallblack"><a name="Heading34"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Create a <tt>RegEx</tt><i> </i>object, which exists within the <tt>System.Text.RegularExpressions</tt> namespace, passing the regular expression in as a parameter to the constructor. Next, call the member method <tt>Match</tt> using the string you want to validate as a parameter to the method. The method returns a <tt>Match</tt><i> </i>object regardless of the outcome. To test whether a match is made, evaluate the Boolean <tt>Success</tt><i> </i>property on that <tt>Match</tt><i> </i>objectas demonstrated in Listing 3.9. It should also be noted that in manycases, the forward slash (\) character is used when working withregular expressions. To avoid compilation errors from inadvertentlyspecifying an invalid control character, use the <tt>@</tt> symbol to turn off escape processing.</span></p>
<h4><span class="smallblack"> Listing 3.9 Validating User Input of a Phone Number Using a Regular Expression </span></h4>
<p><span class="smallblack">using System;<br />using System.Text.RegularExpressions;</p>
<p>namespace _11_RegularExpressions<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> Regex phoneExp = new Regex( @&quot;^\(\d{3}\)\s\d{3}-\d{4}$&quot; );<br /> string input;</p>
<p> Console.Write( &quot;Enter a phone number: &quot; );<br /> input = Console.ReadLine();</p>
<p> while( phoneExp.Match( input ).Success == false )<br /> {<br /> Console.WriteLine( &quot;Invalid input. Try again.&quot; );<br /> Console.Write( &quot;Enter a phone number: &quot; );<br /> input = Console.ReadLine();<br /> }</p>
<p> Console.WriteLine( &quot;Validated!&quot; );<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading35"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Earlier in this chapter I mentioned that you could perform data validation using the static methods within the <tt>System.Char</tt><i> </i>class.You can inspect each character within the input string to ensure itmatches exactly what you are looking for. However, this method of inputvalidation can be extremely cumbersome if you have different inputtypes to validate because it requires custom code for each validation.In other words, using the methods in the <tt>System.Char</tt> class is not recommended for anything but the simplest of data-validation procedures.</span></p>
<p><span class="smallblack">Regular expressions, on the other hand,allow you to perform the most advanced input validation possible, allwithin a single expression. You are in effect passing the parsing ofthe input string to the regular-expression engine and offloading allthe work that you would normally do.</span></p>
<p><span class="smallblack">In Listing 3.9, you can see how you createand use a regular expression to test the validity of a phone numberentered by a user. The regular expression is similar to the previousexpressions used earlier for phone numbers except for the addition ofpositional markers. The regular expression is valid if a user enters aphone number and nothing else. A match is successful when the <tt>Success</tt> property within the <tt>Match</tt> object, which is returned from the <tt>Regex.Match</tt><i> </i>method, is <tt>true</tt>.The only caveat to using regular expressions for input validation isthat even though you know the validation failed, you are unable toquery the <tt>Regex</tt><i> </i>or <tt>Match</tt><i> </i>class to see what part of the string failed.</span></p>
<p><span class="smallblack"><a name="Heading36"></a></span></p>
<h2><span class="smallblack">3.12. Replacing Substrings Using Regular Expressions</span></h2>
<p><span class="smallblack"><b>You want to replace all substrings thatmatch a regular expression with a different substring that also usesregular-expression syntax.</b></span></p>
<p><span class="smallblack"><a name="Heading37"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Create a <tt>Regex</tt><i> </i>object, passing the regular expression used to match characters in the input string to the <tt>Regex</tt><i> </i>constructor. Next,</p>
<p> call the <tt>Regex</tt> method <tt>Replace</tt>,<i> </i>passing the input string to process and the string to replace each match within the input string. You can also use the static <tt>Replace</tt><i> </i>method, passing the regular expression as the first parameter to the method as shown in the last line of Listing 3.10.</span></p>
<h4><span class="smallblack"> Listing 3.10 Using Regular Expressions to Replace Numbers in a Credit Card with xs</span></h4>
<p><span class="smallblack">using System;<br />using System.Text.RegularExpressions;</p>
<p>namespace _12_RegExpReplace<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> Regex cardExp = new Regex( @&quot;(\d{4})-(\d{4})-(\d{4})-(\d{4})&quot; );<br /> string safeOutputExp = &quot;$1-xxxx-xxxx-$4&quot;;<br /> string cardNum;</p>
<p> Console.Write( &quot;Please enter your credit card number: &quot; );<br /> cardNum = Console.ReadLine();</p>
<p> while( cardExp.Match( cardNum ).Success == false )<br /> {<br /> Console.WriteLine( &quot;Invalid card number. Try again.&quot; );<br /> Console.Write( &quot;Please enter your credit card number: &quot; );</p>
<p> cardNum = Console.ReadLine();<br /> }</p>
<p> Console.WriteLine( &quot;Secure Output Result = {0}&quot;, <br /> cardExp.Replace( cardNum, safeOutputExp ));<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading38"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">Although input validation is an extremelyuseful feature of regular expressions, they also work well as textparsers. The previous recipe used regular expressions to verify that aparticular string matched a regular expression exactly. However, youcan also use regular expressions to match substrings within a stringand return each of those substrings as a group. Furthermore, you canuse a separate regular expression that acts on the result of theregular-expression evaluation to replace substrings within the originalinput string. </span></p>
<p><span class="smallblack">Listing 3.10 creates a regular expressionthat matches the format for a credit card. In that regular expression,you can see that it will match on four different groups of four digitsapiece separated by a dash. However, you might also notice that eachone of these groups is surrounded with parentheses. In an earlierrecipe, I mentioned that to use a literal parenthesis, you must escapeit using a backslash because of the conflict with regular-expressiongrouping symbols. In this case, you want to use the grouping feature ofregular expressions. When you place a portion of a regular expressionwithin parentheses, you are creating a numbered group. Groups arenumbered starting with 1 and are incremented for each subsequent group.In this case, there are four numbered groups. These groups are used bythe replacement string, which is contained in the string <tt>safeOutputExp</tt>. To reference a numbered group, use the <tt>$</tt>symbol followed by the number of the group to reference. This sequencerepresents all characters within the input string that match the groupexpression within the regular expression. Therefore, in the replacementstring, you can see that it prints the characters within the firstgroup, replaces the characters in the second and third groups with xs,and finally prints the characters in the fourth group.</span></p>
<p><span class="smallblack">One thing to note is that you can use the <tt>RegEx</tt><i> </i>class to view the groups themselves. If you change the regular expression to &quot;<tt>\d{4}</tt>&quot;, you can then use the <tt>Matches</tt><i> </i>method to enumerate all the groups using the <tt>foreach</tt><i> </i>keyword,as shown in Listing 3.11. In the listing, the program first checks tomake sure at least four matches were made. This number corresponds tofour groups of four digits. Next, it uses a <tt>foreach</tt><i> </i>enumeration on each <tt>Match</tt> object that is returned from the <tt>Matches</tt><i> </i>method. If the match is in the second or third group, the values are replaced with xs; otherwise, the <tt>Match</tt><i> </i>object&#39;s value, the characters within that group, are concatenated to the result string.</span></p>
<h4><span class="smallblack"> Listing 3.11 Enumerating Through the <tt>Match</tt> Collection to Perform Special Operations on Each Match in a Regular Expression </span></h4>
<p><span class="smallblack">static void TestManualGrouping()<br />{<br /> Regex cardExp = new Regex( @&quot;\d{4}&quot; );<br /> string cardNum;<br /> string safeOutputExp = &quot;&quot;;</p>
<p> Console.Write( &quot;Please enter your credit card number: &quot; );<br /> cardNum = Console.ReadLine();</p>
<p> if( cardExp.Matches( cardNum ).Count &lt; 4 )<br /> {<br /> Console.WriteLine( &quot;Invalid card number&quot; );<br /> return;<br /> }</p>
<p> foreach( Match field in cardExp.Matches( cardNum ))<br /> {<br /> if( field.Success == false )<br /> {<br /> Console.WriteLine( &quot;Invalid card number&quot; );<br /> return;<br /> }</p>
<p> if( field.Index == 5 || field.Index == 10 )<br /> {<br /> safeOutputExp += &quot;-xxxx-&quot;;<br /> }<br /> else<br /> {<br /> safeOutputExp += field.Value;<br /> }<br /> }</p>
<p> Console.WriteLine( &quot;Secure Output Result = {0}&quot;, safeOutputExp );<br />}</span>
<p><span class="smallblack"><a name="Heading39"></a></span></p>
<h2><span class="smallblack">3.13. Building a Regular Expression Library</span></h2>
<p><span class="smallblack"><b>You want to create a library of regular expressions that you can reuse in other projects.</b></span></p>
<p><span class="smallblack"><a name="Heading40"></a></span></p>
<h3><span class="smallblack">Technique</span></h3>
<p><span class="smallblack">Use the <tt>CompileToAssembly</tt><i> </i>static method within the <tt>Regex</tt><i> </i>class to compile a regular expression into an assembly. This method uses an array of <tt>RegexCompilationInfo</tt><i> </i>objects that contain any number of regular expressions you want to add to the assembly.</span></p>
<p><span class="smallblack">The <tt>RegexCompilationInfo</tt><i> </i>classcontains a constructor with five fields that you must fill out. Theparameters denote the string for the regular expression; any optionsfor the regular expression, which appear in the <tt>RegexOptions</tt>enumerated type; a name for the class that is created to hold theregular expression; a corresponding namespace; and a Boolean valuespecifying whether the created class should have a public accessmodifier.</span></p>
<p><span class="smallblack">After creating the <tt>RegexCompilationInfo</tt> object, create an <tt>AssemblyName</tt><i> </i>object, making sure to reference the <tt>System.Reflection</tt><i> </i>namespace, and set the <tt>Name</tt><i> </i>property to a name you want the resultant assembly filename to be. Because the <tt>CompileToAssembly</tt><i> </i>creates a DLL, exclude the DLL extension on the assembly name. Finally, place all the <tt>RegexCompilationInfo</tt><i> </i>objects within an array, as shown in Listing 3.12, and call the <tt>CompileToAssembly</tt><i> </i>method. Listing 3.12 demonstrates how to create a <tt>RegexCompilationInfo</tt><i> </i>object and how to use that object to compile a regular expression into an assembly using the <tt>CompileToAssembly</tt> method.</span></p>
<h4><span class="smallblack"> Listing 3.12 Using the <tt>CompileToAssembly</tt> <tt>Regex</tt> Method to Save Regular Expressions in a New Assembly for Later Reuse </span></h4>
<p><span class="smallblack">using System;<br />using System.Text.RegularExpressions;<br />using System.Reflection;</p>
<p>namespace _12_RegExpReplace<br />{<br /> class Class1<br /> {<br /> [STAThread]<br /> static void Main(string[] args)<br /> {<br /> CompileRegex(@&quot;(\d{4})-(\d{4})-(\d{4})-(\d{4})&quot;, @&quot;regexlib&quot; );<br /> }</p>
<p> static void CompileRegex( string exp, string assemblyName )<br /> {<br /> RegexCompilationInfo compInfo = <br /> new RegexCompilationInfo( exp, 0, &quot;CreditCardExp&quot;, &quot;&quot;, true );<br /> AssemblyName assembly = new AssemblyName();<br /> ass</p>
<p>embly.Name = assemblyName;</p>
<p> RegexCompilationInfo[] rciArray = { compInfo };</p>
<p> Regex.CompileToAssembly( rciArray, assembly );<br /> }<br /> }<br />}</span>
<p><span class="smallblack"><a name="Heading41"></a></span></p>
<h3><span class="smallblack">Comments</span></h3>
<p><span class="smallblack">If you use regular expressions regularly,then you might find it advantageous to create a reusable library of theexpressions you tend to use the most. The <tt>Regex</tt><i> </i>class contains a method named <tt>CompileToAssembly</tt> that allows you to compile several regular expressions into an assembly that you can then reference within other projects.</span></p>
<p><span class="smallblack">Internally, you will find a class for eachregular expression you added, all contained within its correspondingnamespace, as specified in the <tt>RegexCompilationInfo</tt><i> </i>object when you created it. Furthermore, each of these classes inherits from the <tt>Regex</tt><i> </i>class so all the <tt>Regex</tt><i> </i>methodsare available for you to use. As you can see, creating a library ofcommonly used regular expressions allows you to reuse and share theseexpressions in a multitude of different projects. A change in a regularexpression simply involves changing one assembly instead of eachproject that hard-coded the regular expression.</span></p>
<p><span class="smallblack"><br /></span></p>
<p class="navigation"><span class="smallblack">&copy; Copyright Pearson Education. All rights reserved.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/05/c-strings-and-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Regular Expressions in C#</title>
		<link>http://www.csharphelp.com/2005/12/regular-expressions-in-c/</link>
		<comments>http://www.csharphelp.com/2005/12/regular-expressions-in-c/#comments</comments>
		<pubDate>Fri, 09 Dec 2005 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[Regex]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=22</guid>
		<description><![CDATA[The following example shows the usage of Regular Expressions in C#. The program basically has all the Validation Programs using Regular Expressions. &#60;pre&#62; /* &#60;howtocompile&#62; csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs &#60;/howtocompile&#62; */ using System.Text.RegularExpressions; using System; class Validation { public static void Main() { string strToTest; Validation objValidate=new Validation(); Console.Write(&#8220;Enter a String to Test for Alphabets:&#8221;); strToTest=Console.ReadLine(); [...]]]></description>
			<content:encoded><![CDATA[<p><strong><span style="font-size: xx-small;"></span></strong><span><a href="http://www.csharphelp.com/bio/prasad.html"><br />
</a></span></p>
<p><span><span class="smallblack">The following example shows the usage of Regular Expressions in C#. The program basically has all the Validation Programs using Regular Expressions.</span></span></p>
<p><span><span class="smallblack">&lt;pre&gt;</span></span></p>
<p><span><span class="smallblack">/*<br />
&lt;howtocompile&gt;<br />
csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs<br />
&lt;/howtocompile&gt;<br />
*/</span></span></p>
<p>using System.Text.RegularExpressions;<br />
using System;</p>
<p>class Validation<br />
{<br />
public static void Main()<br />
{<br />
string strToTest;<br />
Validation objValidate=new Validation();</p>
<p>Console.Write(&#8220;Enter a String to Test for Alphabets:&#8221;);<br />
strToTest=Console.ReadLine();<br />
//Change here to whatever validation you want to perform<br />
if(objValidate.IsAlpha(strToTest))<br />
{<br />
Console.WriteLine(&#8220;{0} is Valid Alpha String&#8221;,strToTest);<br />
}<br />
else<br />
{<br />
Console.WriteLine(&#8220;{0} is not a Valid Alpha String&#8221;,strToTest);<br />
}<br />
}</p>
<p>// Function to test for Positive Integers.</p>
<p>public bool IsNaturalNumber(String strNumber)<br />
{<br />
Regex objNotNaturalPattern=new Regex(&#8220;[^0-9]&#8220;);<br />
Regex objNaturalPattern=new Regex(&#8220;0*[1-9][0-9]*&#8221;);</p>
<p>return !objNotNaturalPattern.IsMatch(strNumber) &amp;&amp;<br />
objNaturalPattern.IsMatch(strNumber);<br />
}</p>
<p>// Function to test for Positive Integers with zero inclusive</p>
<p>public bool IsWholeNumber(string strNumber)<br />
{<br />
Regex objNotWholePattern=new Regex(&#8220;[^0-9]&#8220;);</p>
<p>return !objNotWholePattern.IsMatch(strNumber);<br />
}</p>
<p>// Function to Test for Integers both Positive &amp; Negative</p>
<p>public bool IsInteger(string strNumber)<br />
{<br />
Regex objNotIntPattern=new Regex(&#8220;[^0-9-]&#8220;);<br />
Regex objIntPattern=new Regex(&#8220;^-[0-9]+$|^[0-9]+$&#8221;);</p>
<p>return !objNotIntPattern.IsMatch(strNumber) &amp;&amp;<br />
objIntPattern.IsMatch(strNumber);<br />
}</p>
<p>// Function to Test for Positive Number both Integer &amp; Real</p>
<p>public bool IsPositiveNumber(string strNumber)<br />
{<br />
Regex objNotPositivePattern=new Regex(&#8220;[^0-9.]&#8220;);<br />
Regex objPositivePattern=new Regex(&#8220;^[.][0-9]+$|[0-9]*[.]*[0-9]+$&#8221;);<br />
Regex objTwoDotPattern=new Regex(&#8220;[0-9]*[.][0-9]*[.][0-9]*&#8221;);</p>
<p>return !objNotPositivePattern.IsMatch(strNumber) &amp;&amp;<br />
objPositivePattern.IsMatch(strNumber) &amp;&amp;<br />
!objTwoDotPattern.IsMatch(strNumber);<br />
}</p>
<p>// Function to test whether the string is valid number or not<br />
public bool IsNumber(string strNumber)<br />
{<br />
Regex objNotNumberPattern=new Regex(&#8220;[^0-9.-]&#8220;);<br />
Regex objTwoDotPattern=new Regex(&#8220;[0-9]*[.][0-9]*[.][0-9]*&#8221;);<br />
Regex objTwoMinusPattern=new Regex(&#8220;[0-9]*[-][0-9]*[-][0-9]*&#8221;);<br />
String strValidRealPattern=&#8221;^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$&#8221;;<br />
String strValidIntegerPattern=&#8221;^([-]|[0-9])[0-9]*$&#8221;;<br />
Regex objNumberPattern =new Regex(&#8220;(&#8221; + strValidRealPattern +&#8221;)|(&#8221; + strValidIntegerPattern + &#8220;)&#8221;);</p>
<p>return !objNotNumberPattern.IsMatch(strNumber) &amp;&amp;<br />
!objTwoDotPattern.IsMatch(strNumber) &amp;&amp;<br />
!objTwoMinusPattern.IsMatch(strNumber) &amp;&amp;<br />
objNumberPattern.IsMatch(strNumber);<br />
}</p>
<p>// Function To test for Alphabets.</p>
<p>public bool IsAlpha(string strToCheck)<br />
{<br />
Regex objAlphaPattern=new Regex(&#8220;[^a-zA-Z]&#8220;);</p>
<p>return !objAlphaPattern.IsMatch(strToCheck);<br />
}</p>
<p>// Function to Check for AlphaNumeric.</p>
<p>public bool IsAlphaNumeric(string strToCheck)<br />
{<br />
Regex objAlphaNumericPattern=new Regex(&#8220;[^a-zA-Z0-9]&#8220;);</p>
<p>return !objAlphaNumericPattern.IsMatch(strToCheck);<br />
}</p>
<p>}&lt;/pre&gt;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2005/12/regular-expressions-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

