C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Between: The Between method accepts 2 strings (a and b) and locates each in the source string.
Then: After some error checking, it returns the substring between them. The Before method and After method are similar.
Main: Here an input string "test" is declared. The extensions Between, Before, and After are used on it.
And: The results are printed to the console (with Console.WriteLine) after the parts are extracted.
ConsoleSubstringExtensions.cs implementation: C#
static class SubstringExtensions
{
/// <summary>
/// Get string value between [first] a and [last] b.
/// </summary>
public static string Between(this string value, string a, string b)
{
int posA = value.IndexOf(a);
int posB = value.LastIndexOf(b);
if (posA == -1)
{
return "";
}
if (posB == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= posB)
{
return "";
}
return value.Substring(adjustedPosA, posB - adjustedPosA);
}
/// <summary>
/// Get string value after [first] a.
/// </summary>
public static string Before(this string value, string a)
{
int posA = value.IndexOf(a);
if (posA == -1)
{
return "";
}
return value.Substring(0, posA);
}
/// <summary>
/// Get string value after [last] a.
/// </summary>
public static string After(this string value, string a)
{
int posA = value.LastIndexOf(a);
if (posA == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= value.Length)
{
return "";
}
return value.Substring(adjustedPosA);
}
}
Main method: C#
using System;
class Program
{
static void Main()
{
// Input.
const string test = "DEFINE:A=TWO";
// Test Between.
Console.WriteLine(test.Between("DEFINE:", "="));
Console.WriteLine(test.Between(":", "="));
// Test Before.
Console.WriteLine(test.Before(":"));
Console.WriteLine(test.Before("="));
// Test After.
Console.WriteLine(test.After(":"));
Console.WriteLine(test.After("DEFINE:"));
Console.WriteLine(test.After("="));
}
}
Output
A
A
DEFINE
DEFINE:A
A=TWO
A=TWO
TWO
So: You could use a simple loop along with these extensions to parse a small language.