我尝试在.net中使用regexp来查找和替换某些令牌的字符串,例如
myString =“这是我要更改的文字示例<#somevalue#>和< #othervalue#>”
如何在“<#”和“#>”之间找到包含令牌的文字并为每一个,做一些事情来替换它(搜索数据库并替换任何找到的匹配)?
我想要的结果:
myString =“这是我的文字示例,我想更改someValueFromDb和anotherValueFromDb”
感谢。
答案 0 :(得分:3)
下面是一个使用Regex.Replace
的示例,该示例使用MatchEvaluator
通过在字典中检入指定的令牌来执行替换。如果字典中没有令牌,则文本保持不变。
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace TokenReplacement
{
class Program
{
static void Main(string[] args)
{
string text = "this is a example of my text that I want to change <#somevalue#> and <#anothervalue#>";
var tokens = new Dictionary<string, string>
{
{ "somevalue", "Foo" },
{ "anothervalue", "Bar" }
};
Console.WriteLine(Replace(text, tokens));
}
static string Replace(string input, Dictionary<string, string> tokens)
{
MatchEvaluator evaluator = match =>
{
string token;
if (tokens.TryGetValue(match.Groups[1].Value, out token))
return token;
return match.Value;
};
return Regex.Replace(input, "<#(.*?)#>", evaluator);
}
}
}
答案 1 :(得分:1)
您想要使用接受MatchEvaluator委托的Regex.Replace方法。此委托将允许您动态提供替换文本。
Regex.Replace(yourString, @"\<\#([^#]+)\#\>", delegate(Match match)
{
// Your code here - use match.ToString()
// to get the matched string
});
答案 2 :(得分:1)
感谢所有回复,我在Replace tokens in an aspx page on load找到了答案,这正是我需要的答案
感谢指向正确方向的链接和示例。
private string ParseTagsFromPage(string pageContent)
{
string regexPattern = "{zeus:(.*?)}"; //matches {zeus:anytagname}
string tagName = "";
string fieldName = "";
string replacement = "";
MatchCollection tagMatches = Regex.Matches(pageContent, regexPattern);
foreach (Match match in tagMatches)
{
tagName = match.ToString();
fieldName = tagName.Replace("{zeus:", "").Replace("}", "");
//get data based on my found field name, using some other function call
replacement = GetFieldValue(fieldName);
pageContent = pageContent.Replace(tagName, replacement);
}
return pageContent;
}
答案 3 :(得分:0)
解决方案1
这里有一个相当彻底的基于正则表达式的令牌替换和文档:
http://www.simple-talk.com/dotnet/asp.net/regular-expression-based-token-replacement-in-asp.net/
解决方案2
如果您不想添加那么多代码,这是另一种方法。此代码在配置文件AppSettings部分中查找标记(格式为#MyName#)我在另一个项目中使用了类似的方法在资源和数据库中查找它们(或者在特定优先级中查找所有3个)。如果您愿意,可以通过更改正则表达式和字符串替换行来更改标记的格式。
当然,通过在整个过程中使用正则表达式,仍然可以调整以获得更好的性能。
Public Shared Function ProcessConfigurationTokens(ByVal Source As String) As String
Dim page As Page = CType(Context.Handler, Page)
Dim tokens() As String = GetConfigurationTokens(Source)
Dim configurationName As String = ""
Dim configurationValue As String = ""
For Each token As String In tokens
'Strip off the # signs
configurationName = token.Replace("#"c, "")
'Lookup the value in the configuration (if any)
configurationValue = ConfigurationManager.AppSettings(configurationName)
If configurationValue.Contains(".aspx") OrElse configurationValue.Contains("/") Then
Try
Source = Source.Replace(token, page.ResolveUrl(configurationValue))
Catch
Source = Source.Replace(token, configurationValue)
End Try
Else
'This is an optimization - if the content doesn't contain
'a forward slash we know it is not a url.
Source = Source.Replace(token, configurationValue)
End If
Next
Return Source
End Function
Private Shared Function GetConfigurationTokens(ByVal Source As String) As String()
'Locate any words in the source that are surrounded by # symbols
'and return the list as an array.
Dim sc As New System.Collections.Specialized.StringCollection
Dim r As Regex
Dim m As Match
If Not String.IsNullOrEmpty(Source) Then
r = New Regex("#[^#\s]+#", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
m = r.Match(Source)
While m.Success
sc.Add(m.Groups(0).Value)
m = m.NextMatch
End While
If Not sc.Count = 0 Then
Dim result(sc.Count - 1) As String
sc.CopyTo(result, 0)
Return result
End If
End If
Return New String() {}
End Function