Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do this regex in Python?

Tags:

python

regex

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.

like image 879
TIMEX Avatar asked Sep 05 '26 11:09

TIMEX


2 Answers

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)
like image 97
ChristopheD Avatar answered Sep 07 '26 01:09

ChristopheD


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
like image 24
GreenMatt Avatar answered Sep 07 '26 00:09

GreenMatt