11

I would like to replace words in a string sentence such as:

What $noun$ is $verb$?

What's the regular expression to replace the characters in '$ $' (inclusive) with actual nouns/verbs?

ono
  • 2,984
  • 9
  • 43
  • 85

4 Answers4

20

You don't need a regular expression for that. I would do

string = "What $noun$ is $verb$?"
print string.replace("$noun$", "the heck")

Only use regular expressions when needed. It's generally slower.

Ztyx
  • 14,100
  • 15
  • 78
  • 114
  • 2
    Could string the replaces together as well: `str.replace("$noun$", noun).replace("$verb$", verb)` – ernie Sep 21 '12 at 21:20
  • I have a database of a list of words and the type (Word, type). Type would be noun, verb, etc. I need to check what type of word it is before I replace it. How would you do that? – ono Sep 24 '12 at 14:09
  • Hm, I'm not sure I follow. What type of database? If the database is small I would load it into memory and store it as a dictionary. Looking up the type would simply be `types[word]`. – Ztyx Sep 24 '12 at 21:11
5

Given that you are free to modify $noun$ etc. to your liking, best practise to do this nowadays is probably to using the format function on a string:

"What {noun} is {verb}?".format(noun="XXX", verb="YYY")
Ztyx
  • 14,100
  • 15
  • 78
  • 114
1
In [1]: import re

In [2]: re.sub('\$noun\$', 'the heck', 'What $noun$ is $verb$?')
Out[2]: 'What the heck is $verb$?'
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
1

use a dictionary to hold the regular expression pattern and value. use the re.sub to replace the tokens.

dict = {
   "(\$noun\$)" : "ABC",
   "(\$verb\$)": "DEF"
} 
new_str=str
for key,value in dict.items():
   new_str=(re.sub(key, value, new_str))
print(new_str)

output:

What ABC is DEF?
Golden Lion
  • 3,840
  • 2
  • 26
  • 35