Reputation: 121
Is it possible to include string variable itself in Regex pattern?
text="Sample text is"
st="text"
r=re.findall("[A-Z]+[st]+",text)
print(r[:])
Resaon is I need regex pattern in loop, so st string variable will be not fixed and will be changing, so I can not write Regex pattern as just "text". Or it is not possible? Thanks!
Upvotes: 0
Views: 183
Reputation: 59594
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
>>> import re
>>> text = "Sample text is"
>>> st = "text"
>>> r = re.findall(r"[A-Z]+[%s]+" % re.escape(st), text)
>>> print(r[:])
[]
Note that I am escaping the text.
Upvotes: 1
Reputation: 4501
Just concatenate regexp strings.
import re
pattern1 = "[A-Z]"
pattern2 = "text"
pattern = pattern1 + pattern2
text = "Sample Atext is Ztext"
r = re.findall(pattern, text)
print(r[:])
#['Atext', 'Ztext']
Upvotes: 0
Reputation: 11116
why dont you do :
>>> text="Sample text is"
>>> st="text"
>>> if st in text:
... print('Success')
Upvotes: 0
Reputation: 239443
You can construct the Regular Expression, like this
pattern = re.compile(r"[A-Z]+({})+".format(st))
re.findall(pattern, text)
You can check the created pattern, like this
print pattern.pattern
In the above expression, the value in st
will be substituted in place of {}
. You can read more about it here
Note that, I have changed the [st]
to (st)
, because [st]
will match any character in the word st
. If you want to match the actual word then you might want to group it like I have shown.
But, if all you are trying to do is to check if one string exists in another, then you can use in
operator, like this
if st in text:
Upvotes: 1