In .NET we have a framework that consist of a lot of classes. these classes
can be used when
we want to change the state of an object. So in almost every case whan you
will use a regex you can almost always do the same this by using the classes
that exist in the framework but the code will be greater then using regex.
Hope you understand what I mean.
Not me.
The Regex class and its associated classes provide some
functionality for text matching.
The String class also have some functionality (IndexOf, Substring etc.)
that can be used for the same.
Regex is not about changing state in arbitrary objects. It is text
tool.
I will attach a few examples below.
Arne
========================
using System;
using System.Text.RegularExpressions;
namespace E
{
public class Program
{
private static Regex re = new
Regex(@"(?:<a[^>]+href\s*=\s*[""'])([^""']*)(?:[""'][^>]*>)([^<]*)(?:</a>)",
RegexOptions.IgnoreCase);
public static void Find(string html)
{
foreach(Match m in re.Matches(html))
{
Console.WriteLine("link=" + m.Groups[1].Value);
Console.WriteLine("title=" + m.Groups[2].Value);
}
}
public static void Main(string[] args)
{
Find("bla <a href='foo.html'>Foo</a> bla <a
href='bar.html'>Bar</a> bla");
}
}
}
using System;
using System.Text.RegularExpressions;
namespace E
{
public class Program
{
private static string parsePhp(string php)
{
return "#" + php + "#";
}
private static readonly Regex re = new
Regex(@"(<\?)(.*?)(\?>)", RegexOptions.Compiled | RegexOptions.Singleline);
public static string Parse(string s)
{
string res = s;
foreach(Match m in re.Matches(s))
{
res = res.Replace(m.Groups[0].Value,
parsePhp(m.Groups[2].Value));
}
return res;
}
public static void Main(string[] args)
{
string s = @"<?
include(""inc/db.php"");
include(""inc/layout.php"");
print_header();
?>
<div>
<b>Dette er noget HTML</b>
</div>
<?
print_footer();
?>";
Console.WriteLine(Parse(s));
}
}
}
using System;
using System.Text.RegularExpressions;
namespace E
{
public class Program
{
private static readonly Regex re = new Regex(@"(\d+)
(\d+)/(\d+)", RegexOptions.Compiled);
public static double FractionParse(string s)
{
Match m = re.Match(s);
if(m.Success)
{
return int.Parse(m.Groups[1].Value) +
int.Parse(m.Groups[2].Value) / (double)int.Parse(m.Groups[3].Value);
}
else
{
throw new ArgumentException(s + " is not a valid
fraction");
}
}
public static void Main(string[] args)
{
string s = "5 1/8";
Console.WriteLine(FractionParse(s));
}
}
}
using System;
using System.Text.RegularExpressions;
namespace E
{
public class Program
{
public static void Main(string[] args)
{
string s = "xxx [kEy1] yyy [KeY2] zzz";
string sx = s;
sx = Regex.Replace(sx, @"\[key1\]", "foo",
RegexOptions.IgnoreCase);
sx = Regex.Replace(sx, @"\[key2\]", "bar",
RegexOptions.IgnoreCase);
Console.WriteLine(sx);
}
}
}