已解决!最终用它来做我想做的事:
if (output.Contains("<%TABLE#"))
{
string pattern = @"<%TABLE#([0-9]+)%%>";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(output, pattern, options))
{
int objectID = Int32.Parse(Regex.Match(m.Value, @"\d+").Value);
output = output.Replace(m.Value, ConvertFunction(objectID));
}
}
在我的SQL数据的某些部分(由C#/ ASP.NET网站前端呈现)中是字符串,其中许多可以包含类似<%TABLE#[NUMBER] %%>的模式-[NUMBER]是始终是一个特定的ID 1+。一个字符串中的示例类似于<%TABLE#3 %%>。有时,同一字符串中可能有多个上述模式之一。我最终将尝试执行以下操作:
之所以这样做,是因为每个SQL表都有一个网站页面,用于向最终用户显示其中的数据。格式化数据的方式因表而异,因此每个表都有一个类,用于构建输出字符串并在需要时将其返回。有时,我需要显示当前表中另一个表中的对象。为了解决这个问题,我在字符串中添加了上面的公式,在特定的位置,我希望呈现该对象,以希望识别它并使用其中的ID来抓取适当的对象,构建它,然后替换它模式。
我猜我将不得不使用Regex或其他东西来识别字符串,但是我正在努力寻找最佳的方式来抓取模式,识别其中的数字,调用函数以使用数字,然后用结果替换该特定模式。
下面是一些示例输入以及输出应该是什么。函数ConvertFormula接受一个INT并输出一个STRING。
示例输入/预期输出
示例1:
"Here's some data and more stuff.<%TABLE#3541%%>Here is more text.
<%TABLE#31214%%>And some more."
输出1:
"Here's some data and more stuff." + ConvertFormula(3541) + "Here is more text." + ConvertFormula(31214) + "And some more."
示例2:
"Here's some data and more stuff! Maybe more here!<%TABLE#2%%>Here is more text."
输出2:
"Here's some data and more stuff! Maybe more here!" + ConvertFormula(2) + "Here is more text."
示例3:
"<%TABLE#2%%>This is something completely different with the object call at the start.<TABLE#52%%> and another here."
输出3:
ConvertFormula(2) + "This is something completely different with the object call at the start." + ConvertFormula(52) + " and another here."
示例4:
"There's nothing in this one, no code to find. Just has some text."
输出4:
"There's nothing in this one, no code to find. Just has some text."
示例5:
"This one goes on for a while, like 5132854123 characters, then has a single call right here.<%TABLE#112%%>"
输出5:
"This one goes on for a while, like 5132854123 characters, then has a single call right here." + ConvertFormula(112)
示例6:
"Short <%TABLE#412%%> one."
输出6:
"Short " + ConvertFormula(412) + " one."
示例7:
"Nothing here again."
输出7:
"Nothing here again."
答案 0 :(得分:0)
我猜想这个表达式可能会起作用,
<%TABLE#([0-9]+)%%>
,我们将使用捕获组并收集所需的ID。
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"<%TABLE#([0-9]+)%%>";
string input = @"<%TABLE#3%%>
<%TABLE#1213%%>";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}