Is there an equivalent to 'sscanf()' in .NET?

后端 未结 8 1392
故里飘歌
故里飘歌 2020-12-10 11:46

The .NET Framework gives us the Format method:

string s = string.Format(\"This {0} very {1}.\", \"is\", \"funny\");
// s is now: \"This is very funny.\"


        
相关标签:
8条回答
  • 2020-12-10 12:14

    I came across the same problem, i belive that there is a elegante solution using REGEX... but a came up with function in C# to "UnFormat" that works quite well. Sorry about the lack of comments.

        /// <summary>
        /// Unformats a string using the original formating string. 
        /// 
        /// Tested Situations:
        ///    UnFormat("<nobr alt=\"1\">1<nobr>", "<nobr alt=\"{0}\">{0}<nobr>") : "1"
        ///    UnFormat("<b>2</b>", "<b>{0}</b>") : "2"
        ///    UnFormat("3<br/>", "{0}<br/>") : "3"
        ///    UnFormat("<br/>4", "<br/>{0}") : "4"
        ///    UnFormat("5", "") : "5"
        ///    UnFormat("<nobr>6<nobr>", "<nobr>{0}<nobr>") : "6"
        ///    UnFormat("<nobr>2009-10-02<nobr>", "<nobr>{0:yyyy-MM-dd}<nobr>") : "2009-10-02"
        ///    UnFormat("<nobr><nobr>", "<nobr>{0}<nobr>") : ""
        ///    UnFormat("bla", "<nobr>{0}<nobr>") : "bla"
        /// </summary>
        /// <param name="original"></param>
        /// <param name="formatString"></param>
        /// <returns>If an "unformat" is not possible the original string is returned.</returns>
        private Dictionary<int,string> UnFormat(string original, string formatString)
        {
           Dictionary<int, string> returnList = new Dictionary<int, string>();
    
           try{
              int index = -1;
    
              // Decomposes Format String
              List<string> formatDecomposed = new List<string> (formatString.Split('{'));
              for(int i = formatDecomposed.Count - 1; i >= 0; i--)
              {
                 index = formatDecomposed[i].IndexOf('}') + 1;
    
                 if (index > 0 && (formatDecomposed[i].Length - index) > 0)
                 {
                    formatDecomposed.Insert(i + 1, formatDecomposed[i].Substring(index, formatDecomposed[i].Length - index));
                    formatDecomposed[i] = formatDecomposed[i].Substring(0, index);
                 }
                 else
                    //Finished
                    break;
              }
    
              // Finds and indexes format parameters
              index = 0;
              for (int i = 0; i < formatDecomposed.Count; i++)
              {
                 if (formatDecomposed[i].IndexOf('}') < 0)
                 {
                    index += formatDecomposed[i].Length;
                 }
                 else
                 {
                    // Parameter Index
                    int parameterIndex;
                    if (formatDecomposed[i].IndexOf(':')< 0)
                       parameterIndex = Convert.ToInt16(formatDecomposed[i].Substring(0, formatDecomposed[i].IndexOf('}')));
                    else
                       parameterIndex = Convert.ToInt16(formatDecomposed[i].Substring(0, formatDecomposed[i].IndexOf(':')));
    
                    // Parameter Value
                    if (returnList.ContainsKey(parameterIndex) == false)
                    {
                       string parameterValue;
    
                       if (formatDecomposed.Count > i + 1)
                          if (original.Length > index)
                             parameterValue = original.Substring(index, original.IndexOf(formatDecomposed[i + 1], index) - index);
                          else
                             // Original String not valid
                             break;
                    else
                       parameterValue = original.Substring(index, original.Length - index);
    
                    returnList.Add(parameterIndex, parameterValue);
                    index += parameterValue.Length;
                 }
                 else
                    index += returnList[parameterIndex].Length;
    
                 }
              }
    
              // Fail Safe #1
              if (returnList.Count == 0) returnList.Add(0, original);
           } 
           catch
           {
              // Fail Safe #2
              returnList = new Dictionary<int, string>();
              returnList.Add(0, original);
           }
    
           return returnList;
        }
    
    0 讨论(0)
  • 2020-12-10 12:16

    You could do string[] parts = string.Split(' '), and then extract by the index position parts[1] and parts [3] in your example.

    0 讨论(0)
  • 2020-12-10 12:18

    There's no such method, probably because of problems resolving ambiguities:

    string.Unformat("This {0} very {1}.", "This is very very funny.")
    // are the parameters equal to "is" and "very funny", or "is very" and "funny"?
    

    Regular expression capturing groups are made for this problem; you may want to look into them.

    0 讨论(0)
  • 2020-12-10 12:23

    I reference earlier reply, wrote a sample see following

    string sampleinput = "FirstWord.22222";
    
    Match match = Regex.Match(sampleinput, @"(\w+)\.(\d+)$", RegexOptions.IgnoreCase);
    
    if(match.Success){
    
        string totalmatchstring = match.Groups[0]; // FirstWord.22222
        string firstpart = match.Groups[1]; // FirstWord`
        string secondpart = match.Groups[2]; // 22222
    
    }
    
    0 讨论(0)
  • 2020-12-10 12:29

    If anyone's interested, I've just posted a scanf() replacement for .NET. If regular expressions don't quite cut it for you, my code follows the scanf() format string quite closely.

    You can see and download the code I wrote at http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net.

    0 讨论(0)
  • 2020-12-10 12:30

    Regex with grouping?

    /This (.*?) very (.*?)./
    
    0 讨论(0)
提交回复
热议问题