[英]How to replace some part of this string with vb.net?
我正在尋找創建正則表達式的幫助,以便可以用錨標記替換文本。 文本來自SQL字段(VarChar(max)),其格式設置為:
在上面的文本中,我需要用錨標記替換1994年以后的所有章節。 因此,例如98、553、568和300都將被替換。 下面的代碼查找1994年的整個文本,例如c.98,但是我不確定如何只替換文本中的“ 98”。
Public Shared Function ReplaceChapterTag1(lang As String) As String
Dim l As String = lang
Dim r As Regex = New Regex("199[4-9][/,][/ ][/c]*[/.][/ ][0-9]+(?:\.[0-9]*)?")
Dim applyEvaluator As MatchEvaluator = New MatchEvaluator(AddressOf applyCodeLink)
l = r.Replace(l, applyEvaluator)
Return l
End Function
Private Shared Function applyCodeLink(ByVal m As Match) As String
Dim r As Regex = New Regex("^[0-9]*[\-][0-9]*")
Dim str As String = m.ToString
Dim strReturn As String = ""
Dim match As Match = r.Match(str)
If match.Success Then
strReturn = str
Else
strReturn = "<a href='link?id=" & m.Value & "'>" & m.Value & "</a>"
End If
Return strReturn
End Function
我不確定如何僅替換該文本中的“ 98”。
您可以使用Regex.Replace
。 但是,您需要對構建的正則表達式進行如下調整:
(?<=199[4-9][^;]+)(?<=[/c]*[/.][/\x20]|,\x20)(\d+(?:\.\d*)?)(?=[,;)])
' Input
Dim InputText As String = "..." ' Lorem ipsum...
' Regex
Dim r As Regex = New Regex( _
"(?<=199[4-9][^;]+)" + _
"(?<=[/c]*[/.][/\x20]|,\x20)" + _
"(\d+(?:\.\d*)?)" + _
"(?=[,;)])", _
RegexOptions.IgnoreCase _
Or RegexOptions.CultureInvariant _
Or RegexOptions.Compiled _
)
' This is the replacement string
Dim Replacement As String = "<a href='link?id=$1'>$1</a>"
'' Replace the matched text in the InputText using the replacement pattern
Dim Result As String = r.Replace(InputText,Replacement)
Lorem ipsum dolor就座,安全地執教精英,sius do eiusmod tempor incididunt ut Labore et dolore magna aliqua(1954,c.12; 1968,c.300; 1994,c.98)
Lorem ipsum dolor就座,安全地協助精英人士,seu do eiusmod tempor incididunt ut Labore et dolore magna aliqua(1998,cc。553,568; 2001,cc。17,300)
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua (1954, c. 12; 1968, c. 300; 1994, c. <a href='link?id=98'>98</a>)
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua (1998, cc. <a href='link?id=553'>553</a>, <a href='link?id=568'>568</a>; 2001, cc. 17, 300)
基本上,我的答案中調整后的正則表達式背后的想法是尋找一個或多個數字( \\d+
),並在其后加上一些字符。
我可以自由地簡化和簡化初始正則表達式。 我主要替換為:
[0-9]
與\\d
(space char)
與\\x20
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.