1

I'm using Python3 and trying to use regular expression match a pattern to a value in a variable. Before posting, I looked at:

How to use variables in Python regular expression

--and--

How to use a variable inside a regular expression?

Here's the code:

import re

x = []

x.append("test")
x.append("me")
x.append(x[0] + x[1])

TEXTO = x[2]

print(TEXTO)

if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", "StM", re.IGNORECASE):
    print("Successful match")
else:
    print("Match attempt failed")

if re.search('(.+)'+TEXTO+'(.+)', "StM", re.IGNORECASE):
    print("Successful match")
else:
    print("Match attempt failed")

and it's still failing. Both outputs received are "Match attempt failed"

[dogzilla@localhost ~]$ python3 py1.py 
testme
Match attempt failed
Match attempt failed

What is the proper way to put the variable in question (TEXTO) in the search method?

Thanks!

MGoBlue93
  • 644
  • 2
  • 14
  • 31
  • 4
    What do you expect each of the regexs to be? Do you expect them to match the string `'StM'`? – Brian61354270 Mar 12 '20 at 21:40
  • 2
    I can't really tell what you're trying to do--so i wont touch much-- but I think you mixed up your pattern and your search. Maybe try `re.search('(.+)'+"stM"+'(.+)', TEXTO, re.IGNORECASE)` . I am assuming `TEXTO` is the TextToSearch (which is the second argument). And `sTM` looks like some pattern – Peter Mar 12 '20 at 22:22
  • 1
    Both ways are proper to put the variable into a string. But you need to decide what is your pattern to search and what is your string to search the pattern in. Because now it looks mixed up. – Askold Ilvento Mar 12 '20 at 22:41
  • The I'm inspecting a variable. TEXTO. Inside of TEXTO is "testme". I want to match on "StM"... which are the 3rd, 4th, and 5th characters and should return true. – MGoBlue93 Mar 12 '20 at 23:11

1 Answers1

1

Change the order of your parameters:

if re.search('StM', TEXTO, re.IGNORECASE):
    print("Successful match")
else:
    print("Match attempt failed")
Tomanow
  • 7,247
  • 3
  • 24
  • 52