-1

I am creating a python function with two inputs: a file and a string, in which user can find the location of the string in the file. I figured the best way to do this would be with regular expressions. I have converted the file to one big string (file_string) earlier in the code. For example, let's say the user wants to find "hello" in the file.

input = "hello"
user_input = "r'(" + input + ")'" 
regex = re.compile(user_input) 
for match in regex.finditer(file_string): 
    print(match.start()) 

Creating a new string with r' ' around the input variable is not working. However, the code works perfectly if I replace user_input with r'hello'. How can I convert the string input the user enters to an expression that can be put into re.compile()?

Thanks in advance.

11thal11thal
  • 333
  • 3
  • 13

1 Answers1

1

The r is just part of the syntax for raw string literals, which are useful for simplifying some regular expressions. For example, "\\foo" and r'\foo' produce the same str object. It is not part of the value of the string itself.

All you need to do is create a string with the value of input between ( and ).

input = "hello"
user_input = "(" + input + ")" 

More efficiently (if only marginally so)

user_input = "({})".format(input)

Or more simply in recent versions of Python:

user_input = f'({input})'
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    If the string has any of the special regex expressions, it will not match what is in the file. For example 'abc\d' would match abc1 abc2 and so forth. I'm not sure that's what the question wanted. – Lee Meador Mar 30 '22 at 20:00
  • That's entirely separate issue; I was only correcting the construction of the string. – chepner Mar 30 '22 at 20:15