C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Part A: This is the input string we are matching. Notice how it contains 3 uppercase words, with no spacing in between.
Part B: We see the verbatim string literal syntax. It escapes characters differently than other string literals.
Part C: We call Match on the Regex we created. This returns a Match object. We extract the capture from this object.
String LiteralNote: It is important to use the Groups[1] syntax. The groups are indexed starting at 1, not 0.
C# program that uses Match Groups
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// Part A: the input string we are using.
string input = "OneTwoThree";
// Part B: the regular expression we use to match.
Regex r1 = new Regex(@"One([A-Za-z0-9\-]+)Three");
// Part C: match the input and write results.
Match match = r1.Match(input);
if (match.Success)
{
string v = match.Groups[1].Value;
Console.WriteLine("Between One and Three: {0}", v);
}
}
}
Output
Between One and Three: Two
Here: The input string has the number 12345 in the middle of two strings. We match this in a named group called "middle."
C# program that uses named group
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// ... Input string.
string input = "Left12345Right";
// ... Use named group in regular expression.
Regex expression = new Regex(@"Left(?<middle>\d+)Right");
// ... See if we matched.
Match match = expression.Match(input);
if (match.Success)
{
// ... Get group by name.
string result = match.Groups["middle"].Value;
Console.WriteLine("Middle: {0}", result);
}
// Done.
Console.ReadLine();
}
}
Output
Middle: 12345
Info: This code uses char positions to find the first instance of the left side string, and the last instance of the right.
Caution: It may fail in other cases. But it is likely that this version is faster.
C# program that uses IndexOf
using System;
class Program
{
static void Main()
{
// The input string we are using.
string input = "OneTwoThree";
// Find first instance of this string.
int i1 = input.IndexOf("One");
if (i1 != -1)
{
// Find last instance of the last string.
int i2 = input.LastIndexOf("Three");
if (i2 != -1)
{
// Get the substring and print it.
int start = i1 + "One".Length;
int len = i2 - start;
string bet = input.Substring(start, len);
Console.WriteLine("Between One and Three: {0}", bet);
}
}
}
}
Output
Between One and Three: Two