是否有相当于';sscanf()';在.NET中?
.NET Framework为我们提供了以下方法: 我想要一个“Unformat”函数,类似于:是否有相当于';sscanf()';在.NET中?,.net,string,.net,String,.NET Framework为我们提供了以下方法: 我想要一个“Unformat”函数,类似于: object[] params = string.Unformat("This {0} very {1}.", "This is very funny."); // params is now: ["is", "funny"] 我知道ANSI-C库(vs)中也存在类似的东西 问题是:C#中有类似的东西吗 更新:用正则表达式捕获组不是我需要的解决方案。它们也是一种方式。我正在寻找一个可以在单一格式下
object[] params = string.Unformat("This {0} very {1}.", "This is very funny.");
// params is now: ["is", "funny"]
我知道ANSI-C库(vs)中也存在类似的东西
问题是:C#中有类似的东西吗
更新:用正则表达式捕获组不是我需要的解决方案。它们也是一种方式。我正在寻找一个可以在单一格式下双向工作的系统。放弃某些功能(如类型和格式信息)是可以的。您可以执行string[]parts=string.Split(“”),然后按索引位置提取示例中的部分[1]和部分[3]。带分组的正则表达式
/This (.*?) very (.*?)./
没有这样的方法,可能是因为解决歧义的问题:
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"?
针对这一问题设计了正则表达式;你可能想调查一下。是的。这些被称为“正则表达式”。做这件事的人是
This (?<M0>.+) very (?<M1>.+)\.
这个(?.+)非常(?.+)\。
@mquander:实际上,PHP解决它的方法甚至不同:
$s = "This is very very funny.";
$fmt = "This %s very %s.";
sscanf($s, $fmt, $one, $two);
echo "<div>one: [$one], two: [$two]</div>\n";
//echo's: "one: [is], two: [very]"
$s=“这非常有趣。”;
$fmt=“此%s非常%s.”;
sscanf($s,$fmt,$1,$2);
回显“一:[$1],二:[$2]\n”;
//echo的:“一:[是],二:[非常]”
但也许你的正则表达式评论可以帮助我。我只需要将“This{0}very{1}.”
重写为类似于:新正则表达式(@“^This(.*)very(.*)\.$”
)。这应该通过编程来完成,因此我可以在公共类接口上使用一个格式字符串
顺便说一句:我已经有了一个解析器来查找参数:请参阅的博客条目(是的,我也希望命名参数能够双向工作)。我遇到了同样的问题,我相信使用REGEX有一个优雅的解决方案。。。但是,C#中的一个函数“UnFormat”工作得相当好。很抱歉没有评论
/// <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;
}
//
///使用原始格式化字符串取消格式化字符串。
///
///测试情况:
///不可格式化(“1”,“{0}”):“1”
///不可格式化(“2”,“{0}”):“2”
///不规则(“3
,“{0}
”):“3”
///不规则(“
4”,“
{0}”):“4”
///未格式化(“5”,“5”):“5”
///不可格式化(“6”,“{0}”):“6”
///不可抗力(“2009-10-02”,“{0:yyyy-MM-dd}”):“2009-10-02”
///不可格式化(“,“{0}”):“
///不可格式化(“bla”,“{0}”):“bla”
///
///
///
///如果无法进行“未格式化”,则返回原始字符串。
私有字典未格式化(字符串原始、字符串格式字符串)
{
Dictionary returnList=新字典();
试一试{
int指数=-1;
//分解格式字符串
List formatDecomposed=新列表(formatString.Split('{');
对于(int i=formatDecomposed.Count-1;i>=0;i--)
{
index=formatDecomposed[i].IndexOf('}')+1;
如果(索引>0&(格式分解[i].Length-index)>0)
{
Insert(i+1,formatdecoverated[i]。子字符串(index,formatdecoverated[i]。Length-index));
FormatDecovered[i]=FormatDecovered[i]。子字符串(0,索引);
}
其他的
//完成
打破
}
//查找和索引格式参数
指数=0;
for(int i=0;ii+1)
如果(原始长度>索引)
parameterValue=original.Substring(index,original.IndexOf(formatDecomposed[i+1],index)-index);
其他的
//原始字符串无效
打破
其他的
parameterValue=original.Substring(索引,original.Length-index);
returnList.Add(parameterIndex,parameterValue);
索引+=参数值。长度;
}
其他的
索引+=返回列表[parameterIndex]。长度;
}
}
//故障保护#1
如果(returnList.Count==0)returnList.Add(0,原件);
}
抓住
{
//故障保护#2
returnList=新字典();
返回列表。添加(0,原件);
}
退货清单;
}
如果有人感兴趣,我刚刚发布了一个替代.NET的scanf()。如果正则表达式不能很好地满足您的需要,那么我的代码将非常接近scanf()
格式字符串
您可以查看并下载我在中编写的代码。我参考了前面的回复,编写了一个示例,请参见下文
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
}
这是可行的,但仅适用于此字符串,因为{}值中没有空格。否则索引就会关闭。我认为关键是要绕过RegEx过于复杂和神秘的语法,在不需要复杂性的一般情况下提供一些轻量级和简单的东西。因此,string.format的格式是非常理想的,并且对于希望模式匹配的一般情况是自描述的。在本例中,PHP的行为方式与标准C sscanf相同。Sscanf不会将空格读入%s
变量
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
}