繁体   English   中英

c# 如何从包含格式的字符串中仅提取格式(例如 string = "Printed on {0:dd MMM yyyy}" 并且我想要 dd MMM yyyy

[英]c# How to extract just the format from a string containing a format (e.g. string = "Printed on {0:dd MMM yyyy}" and I want dd MMM yyyy

如果我有一个包含以下格式的字符串(请注意,我无法更改此字符串格式)

var str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}"

我只需要提取格式,例如

"dd MMM yyyy HH:mm:ss"

我知道我可以使用字符串操作或正则表达式来做到这一点,但是有没有一种使用string / format等的 .Net 方法来做到这一点。例如,而不是将给定的字符串插入到我需要提取该格式的格式中。

非常感谢

使用正则表达式

            string str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}";
            string pattern = @"{\d+:(?'date'[^}]+)";
            Match match = Regex.Match(str, pattern);
            string date = match.Groups["date"].Value;

没有正则表达式

            string str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}";

            string[] splitData = str.Split(new char[] { '{' });
            string date = splitData[1].Substring(splitData[1].IndexOf(":") + 1);
            date = date.Replace("}", "");

在打开和关闭大括号上拆分可节省一行代码

            string str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}";

            string[] splitData = str.Split(new char[] { '{', '}' });
            string date = splitData[1].Substring(splitData[1].IndexOf(":") + 1);

您可以通过使用string.Format()传入您专门编写的IFormattable对象列表来提取使用的所有格式的列表,以记录所使用的格式。

/// <summary>
/// A detected argument in a format string
/// </summary>
public class DetectedFormat
{
    public DetectedFormat(int position, string format)
    {
        Position = position;
        Format = format;
    }

    public int Position { get; set; }
    public string Format { get; set; }
}


/// <summary>
/// Implements IFormattable. Used to collect format placeholders
/// </summary>
public class FormatDetector: IFormattable
{
    private int _position;
    List<DetectedFormat> _list;

    public FormatDetector(int position, List<DetectedFormat> list)
    {
        _position = position;
        _list = list;
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        DetectedFormat detectedFormat = new DetectedFormat(_position, format);
        _list.Add(detectedFormat);

        // Return the placeholder without the format
        return "{" + _position + "}";
    }
}

示例代码

// Max index of arguments to support
int maxIndex = 20;

string f = "Text {1:-3} with {0} some {2:0.###} format {0:dd MMM yyyy HH:mm:ss} data";

// Empty list to collect the detected formats
List<DetectedFormat> detectedFormats = new List<DetectedFormat>();

// Create list of fake arguments
FormatDetector[] argumentDetectors = (from i in Enumerable.Range(0, maxIndex + 1)
                                        select new FormatDetector(i, detectedFormats)).ToArray();

// Use string.format with fake arguments to collect the formats
string strippedFormat = string.Format(f, argumentDetectors);

// Output format string without the formats
Console.WriteLine(strippedFormat);

// output info on the formats used
foreach(var detectedFormat in detectedFormats)
{
    Console.WriteLine(detectedFormat.Position + " - " + detectedFormat.Format);
}

输出:

 文本 {1} 和 {0} 一些 {2} 格式的 {0} 数据 \n 1 - -3 \n 0 -  \n 2 - 0.###\n 0 - dd MMM yyyy HH:mm:ss

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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