Python Find entire word in string using regex and user input -


i'm trying find entire word using regex have word i'm searching variable value coming user input. i've tried this:

regex = r"\b(?=\w)" + re.escape(user_input) + r"\b" if re.match(regex, string_to_search[i], re.ignorecase):       <some code>... 

but matches every occurrence of string. matches "var"->"var" correct matches "var"->"var"iable , want match "var"->"var" or "string"->"string"

input: "sword"

string_to_search = "there once swordsmith made sword"

desired output: match "sword" "sword" , not "swordsmith"

you seem want use pattern matches entire string. note \b word boundary needed when wan find partial matches. when need full string match, need anchors. since re.match anchors match @ start of string, need $ (end of string position) @ end of pattern:

regex = '{}$'.format(re.escape(user_input)) 

and use

re.match(regex, search_string, re.ignorcase) 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -