Determines whether a number is a natural number (positive, non-decimal) with Regex - CSharp System.Text.RegularExpressions

CSharp examples for System.Text.RegularExpressions:Match Number

Description

Determines whether a number is a natural number (positive, non-decimal) with Regex

Demo Code


using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Globalization;
using System;/*from w  ww.j  a  v a  2  s .  co m*/

public class Main{
        /// <summary>
        /// Determines whether a number is a natural number (positive, non-decimal)
        /// </summary>
        /// <param name="sItem">The s item.</param>
        /// <returns>
        ///    <c>true</c> if [is natural number] [the specified s item]; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsNaturalNumber(this string sItem)
        {
            Regex notNaturalPattern = new Regex("[^0-9]");
            Regex naturalPattern = new Regex("0*[1-9][0-9]*");

            return !notNaturalPattern.IsMatch(sItem) && naturalPattern.IsMatch(sItem);
        }
}

Related Tutorials