我不確定我在問什么是可能的。我有一個情況
Dim animalList as string = "Dog|Cat|Bird|Mouse"
Dim animal_story_string as string = "One day I was walking down the street and I saw a dog"
Dim hasAnAnimalonList as Boolean
Dim animals() as String = animalList.Split("|")
Dim regex As New Regex("\b" & String.Join("\b|\b", animals) & "\b", RegexOptions.IgnoreCase)
If regex.IsMatch(animal_story_string) Then
hasAnAnimalonList = True
'Here I would like to replace/format the animal found with HTML bold tags so it would look
like "One day I was walking down the street and I saw a <b>dog</>"
End If
在過去,我會回圈遍歷 animalList 中的每個值,如果找到匹配項,則在那時替換它。喜歡
For Each animal As string in animals
' I would replace every animal in the list
' If Cat and Birds and Mouse were not in the string it did not matter
animal_story_string = animal_story_string.Replace(animal,"<b>" animal "</b>"
Next
有沒有辦法使用正則運算式函式來做到這一點?
uj5u.com熱心網友回復:
有沒有辦法使用正則運算式函式來做到這一點?
是的,呼叫Regex.Replace方法并拆分字串以加入結果并創建正則運算式模式,如下所示,您可以使用函式Dog|Cat|Bird|Mouse替換一行中的匹配項。MatchEvaluator
Dim animalList = "Dog|Cat|Bird|Mouse"
Dim regexPattern = String.Join("|", animalList.Split("|"c).Select(Function(x) $"\b{x}\b"))
Dim animal_story_string = "One day I was walking down the street and I saw a dog or maybe a fat cat! I didn't see a bird though."
Dim hasAnAnimalonList = Regex.IsMatch(animal_story_string, regexPattern, RegexOptions.IgnoreCase)
If hasAnAnimalonList Then
Dim replace = Regex.Replace(
animal_story_string,
regexPattern,
Function(m) $"<b>{m.Value}</b>", RegexOptions.IgnoreCase)
Console.WriteLine(replace)
End If
在控制臺中寫道:
One day I was walking down the street and I saw a <b>dog</b> or maybe a fat <b>cat</b>! I didn't see a <b>bird</b> though.
...在 HTML 渲染器中...
有一天我走在街上,我看到了一只狗或者一只肥貓!雖然我沒有看到鳥。
uj5u.com熱心網友回復:
我認為
/(?:^|(?<= ))(Dog|Cat|Bird|Mouse)(?:(?= )|$)/i
甚至
/\b(Dog|Cat|Bird|Mouse)\b/i
見:https ://regex101.com/r/V4Uhg7/1
會做你想做的事嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/498070.html
