How to use Regular Expression in .NET

A

anonieko

Here is an example. For a time server which returns a time field
string, you can extract the time by the following code:




'VB.NET
Imports System.Text.RegularExpressions
'..
Dim s As String
Dim r As Regex
s = "Grennwich time 12:15pm September 1, 2001"
r = New Regex(".*(\d{2}:\d{2}[ap]m)", RegexOptions.IgnoreCase)
If r.Match(s).Success Then
Console.Write(r.Match(s).Result("$1"))




// C#
using System.Text.RegularExpressions;
//...
String s = "Grennwich time 12:15pm September 1, 2001";
Regex r = new Regex(".*(\d{2}:\d{2}[ap]m)", RegexOptions.IgnoreCase);

if ( r.Match(s).Success)
{
Console.Write(r.Match(s).Result("$1"));
}
 
H

Hans Kesting

Here is an example. For a time server which returns a time field
string, you can extract the time by the following code:




'VB.NET
Imports System.Text.RegularExpressions
'..
Dim s As String
Dim r As Regex
s = "Grennwich time 12:15pm September 1, 2001"
r = New Regex(".*(\d{2}:\d{2}[ap]m)", RegexOptions.IgnoreCase)
If r.Match(s).Success Then
Console.Write(r.Match(s).Result("$1"))




// C#
using System.Text.RegularExpressions;
//...
String s = "Grennwich time 12:15pm September 1, 2001";
Regex r = new Regex(".*(\d{2}:\d{2}[ap]m)", RegexOptions.IgnoreCase);

if ( r.Match(s).Success)
{
Console.Write(r.Match(s).Result("$1"));
}

Within C# strings a \ starts an "escape sequence". Use
new Regex(@".*(\d{2}:\d{2}[ap]m)", ...

Hans Kesting
 
J

Jay R. Wren

// C#
using System.Text.RegularExpressions;
//...
String s = "Grennwich time 12:15pm September 1, 2001";
Regex r = new Regex(".*(\d{2}:\d{2}[ap]m)", RegexOptions.IgnoreCase);

if ( r.Match(s).Success)
{
Console.Write(r.Match(s).Result("$1"));
}

I find your use of r.Match(s).Result("$1") interesting. I didn't know
that one could use Match that way. Indeed I am not familiar with the
Result() member.

I typically use the Group() member and its Value property for extracting
data from the Match.

Does anyone know which is more efficient?

Regex.Match(inputstring, "\s+(\d{2}:\d{2}[ap]m)",
RegexOptions.IgnoreCase).Group(1).Value;

vs

Regex.Match(inputstring, "\s+(\d{2}:\d{2}[ap]m)",
RegexOptions.IgnoreCase).Result("$1");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top