简体   繁体   中英

Extract a part of the string based on a pattern C#

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!

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];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM