Created
December 17, 2013 15:00
-
-
Save saitodisse/8006219 to your computer and use it in GitHub Desktop.
C# Regex basics
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; | |
public class RegexBasics | |
{ | |
static public void Main () | |
{ | |
Console.WriteLine("Primeiro método"); | |
Console.WriteLine(".. vai casando com o Match até terminar"); | |
Console.WriteLine(".. e junta tudo no final."); | |
Console.WriteLine("----------------------------"); | |
vai_casando(); | |
Console.WriteLine("----------------------------"); | |
Console.WriteLine("Segundo método"); | |
Console.WriteLine(".. elimine tudo o que não for desejado com o replace"); | |
Console.WriteLine("----------------------------"); | |
elimine_indesejado(); | |
Console.WriteLine("----------------------------"); | |
} | |
public static void vai_casando(){ | |
string text = "tem um numero 2 e o 33 aqui dentro"; | |
string pat = @"\d+"; | |
string finalText = ""; | |
Regex r = new Regex(pat, RegexOptions.IgnoreCase); | |
Match m = r.Match(text); | |
int matchCount = 0; | |
while (m.Success) | |
{ | |
Console.WriteLine("m[{0}] => {1} at position {2}", | |
matchCount++, m.Value, m.Index); | |
finalText += m.Value; | |
m = m.NextMatch(); | |
} | |
Console.WriteLine("final text: [{0}]", finalText); | |
} | |
public static void elimine_indesejado(){ | |
string text = "tem um numero 2 e o 33 aqui dentro"; | |
string pat = @"\D+"; | |
string finalText = Regex.Replace(text, pat, "", RegexOptions.IgnoreCase); | |
Console.WriteLine("final text: [{0}]", finalText); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment