[英]How to get a string from a regex match in vb.net?
我有 :
Dim Text = "some text here ###MONTH-3### some text here ###MONTH-2### some text here"
Dim regex = New System.Text.RegularExpressions.Regex("###MONTH[+-][0-9]###")
For Each match In regex.Matches(Text)
// What to write here ?
// So, that ###MONTH-i### gets replaced with getmonth(i)
// Therefore, final Text will be :
// Text = "some text here" + getmonth(-3) + "some text here" + getmonth(-2) + "some text here"
Next match
我想我已正確解釋了我的問題..
那么,你能幫忙嗎?
我想這就是你想要的。
Dim text As String = "some text here ###MONTH-3### some text here ###MONTH-2### ..."
Dim regex = New System.Text.RegularExpressions.Regex("###MONTH[+-][0-9]###")
return regex.replace(text, AddressOf GetMonthFromMatch)
Function GetMonthFromMatch(ByVal m As Match) As String
' Get the matched string.
Dim matchText As String = m.ToString()
Dim offset As Int = Integer.Parse(matchText.Right(2))
Return getmonth(offset)
End Function
這使用GetMonthFromMatch
委托處理每個匹配,然后調用getmonth
函數。 RegEx.Replace
函數將使用委托替換每個匹配。
首先稍微修改你的正則表達式:
System.Text.RegularExpressions.Regex("###MONTH([+-][0-9])###")
如您所見,我只是在括號中加上數字和+/-。 這樣我們以后可以檢索它們。
所以現在你只需要訪問這些代碼所需的數據(例如-3):
match.Groups(1).Value
編輯:
甚至更簡單的方法:)只需使用替換功能。
在您的示例中,它將如下所示:
Dim regex = New System.Text.RegularExpressions.Regex("###MONTH([+-][0-9])###")
regex.Replace(Text, "getmonth($1)")
1美元引用正則表達式中的第一個括號,因此實際上它將是月份而不是1美元。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.