Rr1n
Rr1n

Reputation: 121

Python String variable itself in Regex pattern

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

Answers (4)

warvariuc
warvariuc

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

Kei Minagawa
Kei Minagawa

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

aelor
aelor

Reputation: 11116

why dont you do :

>>> text="Sample text is"
>>> st="text"
>>> if st in text:
...     print('Success')

Upvotes: 0

thefourtheye
thefourtheye

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

Related Questions