使用正则表达式从数组项列表中替换字符串中的值



我不确定我在问什么是可能的。我有个情况

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

是否有一种方法可以使用Regex函数?

是否有使用Regex函数的方法?

是的,调用Regex.Replace方法并拆分Dog|Cat|Bird|Mouse字符串以加入结果并创建如下所示的regex模式,您可以使用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渲染器中…

有一天我走在街上,我看到一只或者可能是一只胖的!我没有看到一只

我想

/(?:^|(?<= ))(Dog|Cat|Bird|Mouse)(?:(?= )|$)/i

或者

/b(Dog|Cat|Bird|Mouse)b/i

见:https://regex101.com/r/V4Uhg7/1

会做你想要的吗?

相关内容

  • 没有找到相关文章

最新更新