Suppose I have a string of text, of all characters Latin-based. With punctuation.
How do I "find" all the characters and put <strong> tags around it?
hay = The fox jumped up the tree.
needle = "umpe"
In this case, part of the word "jumped" would be highlighted.
Without regex (may be a bit more verbose but also easier to understand):
hay = "The fox jumped up the tree."
needle = "umpe"
print hay.replace(needle, "<strong>%s<strong>" % needle)
EDIT after extra specification: if you want case insensitive replace (which a regular string replace can't do):
import re
hay = "The fox jUMPed up the tree."
needle = "umpe"
regex = re.compile('(%s)' % needle, re.I)
print regex.sub('<strong>\\1</strong>', hay)
Using regular expressions on a simple search expression like this is overkill. However, in case you need a more complicated search, I referenced Python's re module documentation to put together the code below, which I think does what you want:
#!/usr/bin/env python
import re
haystack = "The fox jumped up the tree."
needle = "umpe"
new_text = "<strong>" + needle + "</strong>"
new_haystack = re.sub(needle, new_text, haystack)
print new_haystack
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With