在字符串中使用.NET正则表达式替换文本字符串、文本、正则表达式、NET

2023-09-06 14:34:02 作者:温柔泛滥.

我尝试使用正则表达式在.NET中查找和替换具有一定道理的字符串,例如

MyString的=这是我想改变&LT我的文字的例子;#someValue中#>和< #anothervalue#>

我怎么能找到的标记文本<#和#>,并针对其中每一项,做的东西来取代它(搜索数据库,并更换这些找到的匹配)

结果是我想要的:

MyString的=这是我想改变我的文字的例子someValueFromDb和anotherValueFromDb

感谢。

解决方案

解决方法1

还有这里是一个相当全面的常规EX pression基于令牌替换和文件可供选择:

http://www.simple-talk.com/dotnet/asp.net/regular-ex$p$pssion-based-token-replacement-in-asp.net/

解决方案2

如果你不想增加那么多code,这里是另一种方法。这code查找在配置文件中的AppSettings部分的标记(格式类似于#MYNAME#)我已经用在其他项目中的类似的方法来寻找它们的资源和数据库(或者在一个特定的优先级的所有3)。如果你想通过改变常规EX pression和字符串替换线,你可以改变你的令牌格式。

当然,这仍然可以通过在整个常规EX pressions调整获得更好的性能。

 公共共享功能ProcessConfigurationTokens(来源BYVAL作为字符串)作为字符串
    昏暗的页面作为页= CTYPE(Context.Handler,页)
    昏暗的令牌()作为字符串= GetConfigurationTokens(来源)
    昏暗configurationName作为字符串=
    昏暗configurationValue作为字符串=

    对于每一个片段作为字符串中的标记
        脱光#迹象
        configurationName = token.Replace(#C,)

        查找配置中的值(如果有的话)
        configurationValue = ConfigurationManager.AppSettings(configurationName)

        如果configurationValue.Contains(ASPX)OrElse运算configurationValue.Contains(/),然后
            尝试
                来源= Source.Replace(令牌,page.ResolveUrl(configurationValue))
            抓住
                来源= Source.Replace(令牌,configurationValue)
            结束尝试
        其他
            '这是一个优化 - 如果内容不包含
            正斜杠我们知道这是不是一个网址。
            来源= Source.Replace(令牌,configurationValue)
        结束如果
    下一个

    返回源
端功能

私人共享功能GetConfigurationTokens(来源BYVAL作为字符串)作为字符串()
    找到源头在由#符号包围任何文字
    '并返回列表作为阵列。
    昏暗的SC作为新System.Collections.Specialized.StringCollection

    昏暗为r的正则表达式
    昏暗米作为比赛

    如果不String.IsNullOrEmpty(源),那么

        R =新的正则表达式(#[^#\ s] +#,RegexOptions.Compiled或者RegexOptions.IgnoreCase)
        M = r.Match(来源)
        虽然m.Success

            sc.Add(m.Groups(0).value的)

            M = m.NextMatch
        结束在

        如果尚未sc.Count = 0然后
            昏暗的结果(sc.Count  -  1)作为字符串
            sc.CopyTo(结果,0)

            返回结果
        结束如果
    结束如果

    返回新的String(){}

端功能
 

正则表达式,字符串模板替换

I try to use regexp in .net to find and replace strings with certain token, example

myString = "this is a example of my text that I want to change <#somevalue#> and <#anothervalue#>"

How I can find the text with tokens between "<#" and "#>" and for each of those, do something to replace it (search on a database and replace any of those found matches)?

result that I want:

myString = "this is a example of my text that I want to change someValueFromDb and anotherValueFromDb"

Thanks.

解决方案

Solution 1

There is a fairly thorough regular expression based token replacement and documentation available here:

http://www.simple-talk.com/dotnet/asp.net/regular-expression-based-token-replacement-in-asp.net/

Solution 2

If you don't want to add that much code, here is another approach. This code looks up the tokens (formatted like #MyName#) in the configuration file AppSettings section I have used a similar approach in another project for looking them up in the resources and database (or all 3 in a specific priority). You can change the format of your tokens if you wish by changing the regular expression and string replacement lines.

Of course, this can still be tweaked for better performance by using regular expressions throughout.

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