c#如何仅从包含格式的字符串中提取格式(例如字符串=“打印在{0:dd-MMM-yyyy}”上”,我想要dd-MMM-yyyy
如果我的字符串包含以下格式(注意,我无法更改此字符串格式) 我只需要提取格式,例如c#如何仅从包含格式的字符串中提取格式(例如字符串=“打印在{0:dd-MMM-yyyy}”上”,我想要dd-MMM-yyyy,c#,.net,string,datetime,format,C#,.net,String,Datetime,Format,如果我的字符串包含以下格式(注意,我无法更改此字符串格式) 我只需要提取格式,例如 "dd MMM yyyy HH:mm:ss" 我知道我可以使用字符串操作或正则表达式来实现这一点,但是有没有一种.Net方法可以使用字符串/格式等来实现这一点。例如,我需要提取该格式,而不是将给定字符串插入格式中 非常感谢使用Regex string str = "FormatedDate:Printed {0:dd MMM yyyy HH:mm:ss}"; st
"dd MMM yyyy HH:mm:ss"
我知道我可以使用字符串操作或正则表达式来实现这一点,但是有没有一种.Net方法可以使用字符串
/格式
等来实现这一点。例如,我需要提取该格式,而不是将给定字符串插入格式中
非常感谢使用Regex
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 + "}";
}
}
//
///在格式字符串中检测到参数
///
公共类检测格式
{
公共检测格式(整数位置,字符串格式)
{
位置=位置;
格式=格式;
}
公共int位置{get;set;}
公共字符串格式{get;set;}
}
///
///实现IFormattable。用于收集格式占位符
///
公共类FormatDetector:可附加
{
私人国际职位;
列表(u List),;
公共格式检测器(int位置,列表)
{
_位置=位置;
_列表=列表;
}
公共字符串到字符串(字符串格式,IFormatProvider formatProvider)
{
DetectedFormat DetectedFormat=新的DetectedFormat(_位置,格式);
_列表.添加(detectedFormat);
//返回不带格式的占位符
返回“{”+_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);
}
//要支持的参数的最大索引
int maxIndex=20;
字符串f=“文本{1:-3}带有{0}一些{2:0.####格式{0:dd-MMM-yyy-HH:mm:ss}数据”;
//用于收集检测到的格式的空列表
List detectedFormats=新列表();
//创建伪参数列表
FormatDetector[]argumentDetectors=(从可枚举范围(0,maxIndex+1)中的i开始)
选择新的FormatDetector(i,detectedFormats)).ToArray();
//使用带有伪参数的string.format收集格式
string strippedFormat=string.Format(f,argument);
//不带格式的输出格式字符串
Console.WriteLine(strippedFormat);
//输出有关所用格式的信息
foreach(detectedFormats中的var detectedFormat)
{
Console.WriteLine(detectedFormat.Position+“-”+detectedFormat.Format);
}
输出:
带有{0}某些{2}格式{0}数据的文本{1}
1 - -3
0 -
2 - 0.###
0-dd mm yyyy HH:mm:ss
我不相信.Net提供了魔力。如果你有一个非泛型的字符串(比如你的),您必须执行一些字符串操作才能获得所需的内容。在这里使用正则表达式有什么低效之处?您至少可以使用它来解析datetime数据,然后将字符串操作为.NET可以解析为datetime对象的内容。谁说我要解析为datetime对象?我只是想知道是否有一种方法可以解析为由于.Net使用格式将其应用于插值字符串,因此可能可以访问它。如果不是这样,我将使用正则表达式/字符串操作。请问您为什么需要这样做?我使用一个
json
文件,其中包含一些字段,例如“FormattedDate:Printed”{0:dd-MMM-yyyy-HH:mm:ss}“
。我需要将它(实际上是使用插值字符串的任何组合)转换为HTML文档,使用thymeleaf表示日期(例如,
,谢谢她提出了一种不包含正则表达式的方法。当然,我倾向于同意这是一个可靠的解决方案,我们不应该再发明轮子。我添加了一个非正则表达式的解决方案。这也是我的解决方案,但我不想挖走你。这也是非常好的代码。我可以告诉你,你已经做了很长时间了。这很完美,这正是我想要的。谢谢
// 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);
}
Text {1} with {0} some {2} format {0} data
1 - -3
0 -
2 - 0.###
0 - dd MMM yyyy HH:mm:ss