0

I have a function which accepts regular expression and then does regular exp match on the target string. In python the regular expression has to be prefixed with 'r'. I am not able to do that.

r^[a-zA-Z0-9]{3}_TREE is what I want to get. My function receives '^[a-zA-Z0-9]{3}_TREE' 

If I do

'r'+ '^[a-zA-Z0-9]{3}_TREE' then it 'r' also becomes string which is not.

Can you please help me?

But my regex doesn't have escape sequences so using r doesn't matter but then I see another problem. If I am hardcoding the regex in the match statement it is working, but if I call the function and receive it as a string and then use in the function it is not working. What am I doing wrong?

Bavaraa
  • 61
  • 1
  • 1
  • 7

2 Answers2

1

Just pass the argument like normal function is ok, since 'r' prefix declares a raw string, which just escapes backslashes and convert to a normal str type.

For this particular example, the 'r' is actually not needed. Try

import re
pattern1 = "^[a-zA-Z0-9]{3}_TREE"
pattern2 = r"^[a-zA-Z0-9]{3}_TREE"
txt1 = "AVL_TREE"
txt2 = "WHAT IS AVL_TREE"
pattern = re.compile(pattern1)
print(pattern.findall(txt1))
print(pattern.findall(txt2))

pattern = re.compile(pattern2)
print(pattern.findall(txt1))
print(pattern.findall(txt2))

def my_regex(pattern,txt):
    pattern = re.compile(pattern)
    print(pattern.findall(txt))

my_regex(pattern1,txt1)
my_regex(pattern1,txt2)
my_regex(pattern2,txt1)
my_regex(pattern2,txt2)
chellya
  • 376
  • 2
  • 8
  • Thanks chellya, so the only problem was I was not compiling the pattern before passing to the function and after receiving in function – Bavaraa Oct 10 '17 at 08:45
0

Yes I agree that I don't need 'r' as I don't have escape backlashes. when I call my function which has the match() function I pass '^[a-zA-Z0-9]{3}_TREE'. In the function when I receive it and print I get \^[a-zA-Z0-9]{3}_ECOLI (a backslash appended in the front) Why is this happening?

Bavaraa
  • 61
  • 1
  • 1
  • 7