Home > front end >  Using Regex to replace a value in a string from a list of items in array
Using Regex to replace a value in a string from a list of items in array

Time:07-03

I'm not sure I'm asking what is possible. I have a situation

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

In the past I would loop each value in the animalList and if a match is found replace it at that time. Like

     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

Is there a way to do it using a Regex function?

CodePudding user response:

I think

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

or even

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

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

will do what you want?

CodePudding user response:

Is there a way to do it using a Regex function?

Yes, call Regex.Replace method and split the Dog|Cat|Bird|Mouse string to join the result and create the regex pattern as shown below, you can replace the matches in one line using a MatchEvaluator function.

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

Writes in the console:

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.

... and in HTML renderer...

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.

  • Related