Skip to content

Instantly share code, notes, and snippets.

@codeimpossible
Created March 18, 2014 05:53
Show Gist options
  • Save codeimpossible/9614244 to your computer and use it in GitHub Desktop.
Save codeimpossible/9614244 to your computer and use it in GitHub Desktop.
Some c# extension methods I wrote a really long time ago...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace CodeImpossible.Core
{
/// <summary>
/// Object extension methods
/// </summary>
public static class ObjectExt
{
/// <summary>
/// Returns TRUE if an objects value is <cref="System.null" /> and FALSE if the object has been initiated.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static bool IsNull(this object o)
{
return o == null;
}
}
/// <summary>
/// String extension methods
/// </summary>
public static class StringExt
{
/// <summary>
/// Replaces the format item in a specified System.String with the text
/// equivelent of the value from a corresponding System.Object reference in a specified array
/// </summary>
/// <param name="formatProvider">a composite format string</param>
/// <param name="t">An System.Object to format</param>
/// <exception cref="System.ArgumentNullException" />
/// <exception cref="System.FormatException" />
/// <returns>a compiled string</returns>
public static string Combine(this string formatProvider, params object[] args)
{
return String.Format(formatProvider, args);
}
/// <summary>
/// Executes a passed Regular Expression against a string and returns the result of the match
/// </summary>
/// <param name="s">the target string</param>
/// <param name="RegEx">a System.String containing a regular expression</param>
/// <returns>true if the regular expression matches the target string and false if it does not</returns>
public static bool IsMatch(this string s, string RegEx)
{
return new Regex(RegEx).IsMatch(s);
}
/// <summary>
/// Executes a passed Regular Expression against a string and returns the result of the match
/// </summary>
/// <param name="s">the target string</param>
/// <param name="RegEx">any Regular Expression object</param>
/// <returns>true if the regular expression matches the target string and false if it does not</returns>
public static bool IsMatch(this string s, Regex RegEx)
{
return RegEx.IsMatch(s);
}
/// <summary>
/// Checks to see if the string contains a valid email address.
/// </summary>
/// <param name="s">the target string</param>
/// <returns>Returns TRUE if the string contains an email address and it is valid or FALSE if the string
/// has no email address or it is invalid</returns>
public static bool IsValidEmail(this string s)
{
return s.IsMatch(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
}
/// <summary>
/// Checks to see if the string is all numbers
/// </summary>
/// <param name="s">the target string</param>
/// <returns>Returns TRUE if the string is all numbers or FALSE if the string has no numbers or is all alpha characters.</returns>
public static bool IsInteger(this string s)
{
return !s.IsMatch("[^0-9-]") && s.IsMatch("^-[0-9]+$|^[0-9]+$");
}
/// <summary>
/// Tests a string to see if it is a Positive Integer
/// </summary>
/// <param name="strNumber"></param>
/// <returns></returns>
public static bool IsNaturalNumber(this string strNumber)
{
return !strNumber.IsMatch("[^0-9]") && strNumber.IsMatch("0*[1-9][0-9]*");
}
/// <summary>
/// Tests a string to see if it is a Positive Integer with zero inclusive
/// </summary>
/// <param name="strNumber"></param>
/// <returns></returns>
public static bool IsWholeNumber(this string strNumber)
{
return !strNumber.IsMatch("[^0-9]");
}
/// <summary>
/// Tests a string to see if it a Positive number both Integer & Real
/// </summary>
/// <param name="strNumber"></param>
/// <returns></returns>
public static bool IsPositiveNumber(this string strNumber)
{
return !strNumber.IsMatch("[^0-9.]") && strNumber.IsMatch("^[.][0-9]+$|[0-9]*[.]*[0-9]+$") && !strNumber.IsMatch("[0-9]*[.][0-9]*[.][0-9]*");
}
/// <summary>
/// Tests a string to see if it is a number
/// </summary>
/// <param name="strNumber"></param>
/// <returns></returns>
public static bool IsNumber(this string strNumber)
{
string strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
string strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
return !strNumber.IsMatch("[^0-9.-]") && !strNumber.IsMatch("[0-9]*[.][0-9]*[.][0-9]*") &&
!strNumber.IsMatch("[0-9]*[-][0-9]*[-][0-9]*") && strNumber.IsMatch("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
}
/// <summary>
/// Tests a string to see if it contains alpha characters
/// </summary>
/// <param name="strToCheck"></param>
/// <returns></returns>
public static bool IsAlpha(this string strToCheck)
{
return !strToCheck.IsMatch("[^a-zA-Z]");
}
/// <summary>
/// Tests a string to see if it contains alpha and numeric characters
/// </summary>
/// <param name="strToCheck"></param>
/// <returns></returns>
public static bool IsAlphaNumeric(this string strToCheck)
{
return !strToCheck.IsMatch("[^a-zA-Z0-9]");
}
/// <summary>
/// Checks to see if a System.String value is a string representation of a boolean value.
/// </summary>
/// <param name="s">the target string</param>
/// <returns>true if the System.String value is truthy or false if not</returns>
public static bool IsBoolean(this string s)
{
string _lower = s.ToLower();
return _lower.IsMatch("[true]|[false]|[0]|[1]");
}
/// <summary>
/// Replicates a System.String the passed number of times and returns the value
/// </summary>
/// <param name="s">the target System.String</param>
/// <param name="times">the number of times to replicate the string</param>
/// <returns>the replicated string</returns>
public static string Replicate(this string s, int times)
{
string hold = String.Empty;
times.Times(delegate(int i)
{
hold += s;
});
return hold;
}
/// <summary>
/// Converts a System.String value to a boolean type.
/// </summary>
/// <param name="s"></param>
/// <returns>Returns the boolean representation of the strings value or FALSE if the string is not a valid boolean.</returns>
/// <exception cref="System.FormatException" />
/// <remarks>Calls extension IsBoolean()</remarks>
public static bool InterpretAsBoolean(this string s)
{
if (s.IsBoolean())
{
return Convert.ToBoolean(s);
}
return false;
}
/// <summary>
/// Converts a System.String value to an integer type.
/// </summary>
/// <param name="s"></param>
/// <returns>Returns the integer representation of the strings value or -1 if the string is not a valid integer.</returns>
/// <exception cref="System.FormatException" />
/// <remarks>Calls extension IsNumeric()</remarks>
public static int InterpretAsInteger(this string s)
{
if (s.IsInteger())
{
return Convert.ToInt32(s);
}
return -1;
}
/// <summary>
/// Converts a System.String to proper case.
/// </summary>
/// <param name="s">the target string</param>
/// <exception cref="System.FormatException" />
/// <returns>a properly cased System.String</returns>
public static string Capitalize(this string s)
{
string result = String.Empty;
foreach (string p in s.Split(' '))
{
if (p != String.Empty)
result += p.Substring(0, 1).ToUpper() + p.Substring(1) + " ";
}
return result;
}
/// <summary>
/// Searches a given System.String for the next to last occurance of another System.String
/// </summary>
/// <param name="s">the string to search</param>
/// <param name="index">the string to look for</param>
/// <returns>the position of the occurance</returns>
public static int NextToLastIndexOf(this string s, string index)
{
int i = 0;
int end = s.LastIndexOf(index);
if (end == -1) return end;
do
{
i = s.IndexOf(index);
}
while (i > -1 && i < end);
return i;
}
/// <summary>
/// Allows iterating over every occurrence of the given pattern (which can be a string or a regular expression). Returns the original string.
/// </summary>
/// <param name="s">the string to scan</param>
/// <param name="RegularExpression"></param>
/// <param name="Delegate">function delegate that will process the matched items</param>
/// <returns>The original string.</returns>
public static string Scan(this string s, string RegularExpression, Action<string> Delegate)
{
Regex _regex;
if (s.IsMatch(RegularExpression, out _regex))
{
MatchCollection mc = _regex.Matches(s, 0);
foreach (Match m in mc)
{
Delegate(m.Value);
}
}
return s;
}
/// <summary>
/// Allows iterating over every occurrence of the given pattern (which can be a string or a regular expression). Returns the original string.
/// </summary>
/// <param name="s">the strig to scan</param>
/// <param name="RegularExpression">The pattern to match against</param>
/// <param name="Delegate">function delegate that will process the matched items</param>
/// <returns>The original string</returns>
public static string Scan(this string s, Regex RegularExpression, Action<string> Delegate)
{
if (RegularExpression.IsMatch(s))
{
MatchCollection mc = RegularExpression.Matches(s, 0);
foreach (Match m in mc)
{
Delegate(m.Value);
}
}
return s;
}
/// <summary>
/// Checks if a string is empty or null. Returns false if the string has data
/// </summary>
/// <param name="s">the string to check</param>
/// <returns>false if the string has data</returns>
public static bool HasValue(this string s)
{
if (!s.IsNull() || s.Trim().Equals(String.Empty)) return false;
return true;
}
/// <summary>
/// Checks if a string has any trailing or leading whitespace
/// </summary>
/// <param name="s">the string to check</param>
/// <returns>true if the string can be trimmed</returns>
public static bool CanBeTrimmed(this string s)
{
return !s.Equals(s.Trim());
}
}
/// <summary>
/// Timespan extension methods
/// </summary>
public static class TimespanExt
{
/// <summary>
/// Determines a date of time from a timespan
/// </summary>
/// <param name="val">the target timespan</param>
/// <example>
/// TimeSpan.FromHours(2.0).Ago(); //two hours in the past
/// </example>
/// <returns>a datetime object</returns>
public static DateTime Ago(this TimeSpan val)
{
return DateTime.Now.Subtract(val);
}
/// <summary>
/// Determines a date of time from a timespan
/// </summary>
/// <param name="val">the target timespan</param>
/// <example>
/// TimeSpan.FromHours(2.0).FromNow(); //two hours in the future
/// </example>
/// <returns>a datetime object</returns>
public static DateTime FromNow(this TimeSpan val)
{
return DateTime.Now.Add(val);
}
}
/// <summary>
/// Integer extension methods
/// </summary>
public static class IntegerExt
{
/// <summary>
/// Executes a delegate method the specified number of times
/// </summary>
/// <param name="i">the number of times to execute the delegate</param>
/// <param name="function">the delegate to execute</param>
public static void Times(this int i, Action function)
{
for (int ii = 0; ii <= i - 1; ii++)
{
function();
}
}
/// <summary>
/// Executes a delegate method the specified number of times and passes the iteration counter to the delegate
/// </summary>
/// <param name="i">the number of times to execute the delegate</param>
/// <param name="function">the delegate to execute</param>
public static void Times(this int i, Action<int> function)
{
for (int ii = 0; ii <= i - 1; ii++)
{
function(ii);
}
}
/// <summary>
/// Converts a number to it's comma seperated representation
/// </summary>
/// <param name="i">the number to convert</param>
/// <returns>a System.String containing the comma seperated representation</returns>
public static string Commaify(this int i)
{
string number = i.ToString();
string natLangNum = String.Empty;
string numberPieces = String.Empty;
int backPos = 0, counter = 1;
for (int ii = 0; ii <= number.Length - 1; ii++)
{
backPos = number.Length - ii;
numberPieces = number.Substring(backPos - 1, 1) + numberPieces;
if (counter % 3 == 0)
{
natLangNum += "," + numberPieces;
numberPieces = String.Empty;
counter = 1;
}
else
{
counter++;
}
}
if( numberPieces != String.Empty)
natLangNum += "," + numberPieces;
return natLangNum.Substring(1);
}
/// <summary>
/// Converts a number to it's natural language equivelent
/// </summary>
/// <param name="i">the number to convert</param>
/// <returns>a System.String containing the converted representation</returns>
public static string ToNaturalLanguage(this int i)
{
if (i == 0) return "zero";
string[] int2str1 = new string[] { String.Empty, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
string[] int2str2 = new string[] { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
string[] int2str3 = new string[] { String.Empty, String.Empty, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
string[] int2str4 = new string[] { "hundred", "thousand", "million", "billion", "trillion", "quadrillion" };
string natLangNum = String.Empty;
if (i <= int2str1.Length - 1) return int2str1[i];
if (i > 9 && i < 20) return int2str2[i - 10];
string number = i.ToString();
string[] Arr = i.Commaify().Split(',');
for (int ii = Arr.Length - 1; ii >= 0; --ii)
{
string result = String.Empty, piece = Arr[ii], suffix = int2str4[Arr.Length];
if (piece.Length == 3 && Arr.Length >= 1)
{
int firstPos = piece.Substring(0, 1).InterpretAsInteger(); // Convert.ToInt32(piece.Substring(0, 1));
int secondPos = piece.Substring(1, 1).InterpretAsInteger(); // Convert.ToInt32(piece.Substring(1, 1));
int thirdPos = piece.Substring(2, 1).InterpretAsInteger(); // Convert.ToInt32(piece.Substring(2, 1));
int secondthirdPos = piece.Substring(1, 2).InterpretAsInteger(); // Convert.ToInt32(piece.Substring(1, 2));
string firstPosStr = firstPos == 0 ? String.Empty : int2str1[firstPos] + " " + int2str4[0];
string secondPosStr = secondPos == 0 ? String.Empty : int2str1[secondPos] == String.Empty ? int2str2[(secondthirdPos < 11 ? secondthirdPos + 10 : secondthirdPos) - 10] : int2str3[secondPos];
string thirdPosStr = thirdPos == 0 ? String.Empty : int2str1[secondPos] == String.Empty ? String.Empty : "-" + int2str1[thirdPos];
result = firstPosStr.Trim() + (secondPosStr != String.Empty ? " " : String.Empty) + secondPosStr.Trim() + thirdPosStr.Trim() + " " + (ii == 0 ? String.Empty : int2str4[ii].Trim()) + " ";
}
else if (piece.Length < 3 && Arr.Length > 1 && ii > 0)
{
int firstPos = Convert.ToInt32(piece);
string firstPosStr = firstPos < 10 ? int2str1[firstPos] : firstPos > 19 ? int2str3[firstPos / 10] : int2str2[firstPos - 10];
result = firstPosStr.Trim() + " " + int2str4[ii].Trim() + " ";
}
natLangNum += result;
}
return natLangNum.Trim();
}
/// <summary>
/// Generates a TimeSpan representing a set number of Minutes
/// </summary>
/// <param name="i">the number of minutes to set in the timespan</param>
/// <returns>a System.TimeSpan object</returns>
public static TimeSpan Minutes(this int i)
{
return new TimeSpan(0, i, 0);
}
/// <summary>
/// Generates a TimeSpan representing a set number of Hours
/// </summary>
/// <param name="i">the number of hours to set in the timespan</param>
/// <returns>a System.TimeSpan object</returns>
public static TimeSpan Hours(this int i)
{
return new TimeSpan(i, 0, 0);
}
/// <summary>
/// Generates a TimeSpan representing a set number of Seconds
/// </summary>
/// <param name="i">the number of seconds to set in the timespan</param>
/// <returns>a System.TimeSpan object</returns>
public static TimeSpan Seconds(this int i)
{
return new TimeSpan(0, 0, i);
}
/// <summary>
/// Generates a TimeSpan representing a set number of Days
/// </summary>
/// <param name="i">the number of days to set in the timespan</param>
/// <returns>a System.TimeSpan object</returns>
public static TimeSpan Days(this int i)
{
return new TimeSpan(i, 0, 0, 0);
}
}
}
@CamiloBernal
Copy link

Hey !, great. Thank you very much for sharing. I had problems with first "scan" method because you not put a 'IsMatch "with a parameter of type" out ". Otherwise, it was very helpful to me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment