Last active
June 6, 2018 01:10
-
-
Save relliv/9c6beb3d441c94e99e3cd91dffb457b9 to your computer and use it in GitHub Desktop.
C# Deformat method for String.Format (Extented Method)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Reversing class | |
/// </summary> | |
public static class ReversingClass | |
{ | |
/// <summary> | |
/// String.Format reverser | |
/// </summary> | |
/// <param name="string">string value</param> | |
/// <param name="template">format template</param> | |
/// <returns>List<string></returns> | |
public static List<string> ReverseStringFormat(this string @string, string template) | |
{ | |
// create matches list | |
List<string> matches = null; | |
// replace slashes | |
template = Regex.Replace(template, @"[\\\^\$\.\|\?\*\+\(\)]", p => "\\" + p.Value); | |
// replace index numbers | |
var pattern = "^" + Regex.Replace(template, @"\{[0-9]+\}", "(.*?)") + "$"; | |
// get matches | |
var match = new Regex(pattern).Match(@string); | |
// if there is not any match, return null matches | |
if (match.Groups.Count <= 0) return matches; | |
// set list | |
matches = new List<string>(); | |
// loop with match count | |
for (var i = 1; i < match.Groups.Count; i++) | |
{ | |
// add to matches list | |
matches.Add(match.Groups[i].Value); | |
} | |
return matches; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fomatted string | |
var myString = String.Format("My name is {0} and I am {1} years old.", "Yıldıray", "20"); | |
// deformatted string as list<string> | |
var parsedString = myString.ReverseStringFormat("My name is {0} and I am {1} years old."); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment