Home > Mobile >  Extract a part of the string based on a pattern C#
Extract a part of the string based on a pattern C#

Time:12-14

I'm trying to extract a part of a string in C# based on the specific pattern.

Examples :

pattern1 => string1_string2_{0}_string3_string4.txt should return string value of "{0}"

 toto_tata_2021_titi_tutu.txt should return 2021

pattern2 => string1_string2_string3_{0}_string4.csv should return string value of "{0}"

 toto_tata_titi_2022_tutu.csv should return 2022

Thanks!

CodePudding user response:

string pattern = "string1_string2_{0}_string3_string4.txt";
int indexOfPlaceholder = pattern.IndexOf("{0}");
int numberOfPreviousUnderscores = pattern.Substring(0, indexOfPlaceholder).Split('_', StringSplitOptions.RemoveEmptyEntries).Length;
string stringToBeMatched = "toto_tata_2021_titi_tutu.txt";
string stringAtPlaceholder = stringToBeMatched.Split('_')[numberOfPreviousUnderscores];

CodePudding user response:

using the library "System.Text.RegularExpressions":

public static string ExtractYear(string s)
{
    var match = Regex.Match(s, "_([0-9]{4})_");
    if (match.Success)
    {
        return match.Groups[1].Value;
    }
    else
    {
        throw new ArgumentOutOfRangeException();
    }
}

like that?
For Situations like that Regex sound like a great Option.

  • Related