Last active
March 28, 2024 05:52
-
-
Save normanlmfung/814f78f5336d65f043eac8ac2dd7b0bd to your computer and use it in GitHub Desktop.
csharp_regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text.RegularExpressions; | |
class Program | |
{ | |
static void Main() | |
{ | |
// https://www.mikesdotnetting.com/article/46/c-regular-expressions-cheat-sheet | |
string emailAddress = "[email protected]"; | |
string emailPattern = @"^\w+@[a-zA-Z_]+\.[a-zA-Z]{2,3}$"; | |
// string emailPattern = @"^\w+@\w+\.\w+$"; // This also works. | |
if (Regex.IsMatch(emailAddress, emailPattern)) | |
{ | |
Console.WriteLine("Valid email address."); | |
} | |
else | |
{ | |
Console.WriteLine("Invalid email address."); | |
} | |
string phoneNumber = "(123) 456-7890"; | |
string phonePattern = @"\((\d{3})\)"; | |
Match match1 = Regex.Match(phoneNumber, phonePattern); | |
if (match1.Success) | |
{ | |
string areaCode = match1.Groups[1].Value; | |
Console.WriteLine("Area code: " + areaCode); | |
} | |
else | |
{ | |
Console.WriteLine("Area code not found."); | |
} | |
string text = "My phone number is (123) 456-7890."; | |
string phonePattern2 = @"\((\d{3})\) (\d{3})-(\d{4})"; // \( (\d{3}) \) | |
Match match = Regex.Match(text, phonePattern2); | |
if (match.Success) | |
{ | |
string areaCode = match.Groups[1].Value; | |
string firstPart = match.Groups[2].Value; | |
string secondPart = match.Groups[3].Value; | |
Console.WriteLine($"Area Code: {areaCode}"); | |
Console.WriteLine($"First Part: {firstPart}"); | |
Console.WriteLine($"Second Part: {secondPart}"); | |
} | |
else | |
{ | |
Console.WriteLine("Phone number not found."); | |
} | |
// Multi-part extraction | |
/* | |
Month Month Code | |
January F | |
February G | |
March H | |
April J | |
May K | |
June M | |
July N | |
August Q | |
September U | |
October V | |
November X | |
December Z | |
Examples: https://www.cmegroup.com/markets/cryptocurrencies/bitcoin/bitcoin.quotes.html#venue=globex | |
*/ | |
string futureCode = "BTCH24"; | |
string futureCodePattern = @"^(?<token>[A-Z]{3})(?<futureMonthCode>[A-Z])(?<year>\d+)+$"; | |
Match futureCodeMatch = Regex.Match(futureCode, futureCodePattern); | |
if (futureCodeMatch.Success) | |
{ | |
string token = futureCodeMatch.Groups["token"].Value; | |
string monthCode = futureCodeMatch.Groups["futureMonthCode"].Value; | |
int year = Convert.ToInt32(futureCodeMatch.Groups["year"].Value); | |
Console.WriteLine($"futureCode: {futureCode}, token: {token}, monthCode: {monthCode}, year: {year}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment