-1

Is there any way to exucute regex string as a code.

import re

list1 = ["guru99 get", "guru99 give", "guru Selenium"]
for element in list1:
    z = """re.match("(g\w+)\W(g\w+)", element)""" ##this needs to be in string as i am taking from file.
    if z:
        print((z.groups()))

Error:

Traceback (most recent call last):
  File "/u/vithals/Desktop/Waver/regex_worked.py", line 7, in <module>
    print((z.groups()))
AttributeError: 'str' object has no attribute 'groups'
  • What is your desired output? – U13-Forward Dec 20 '20 at 03:50
  • 3
    Try using `eval`: https://stackoverflow.com/a/701807/5745962 – Turtlean Dec 20 '20 at 03:53
  • 3
    @Turtlean [Using `eval` is bad practice](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice) – U13-Forward Dec 20 '20 at 03:54
  • 2
    I wouldn't do that in real-life code, though I thought that either `eval` or `exec` could do what Visha is trying to. Thanks for sharing your thoughts on the subject – Turtlean Dec 20 '20 at 03:58
  • eval is helping .thanks – Visha Visahli Dec 20 '20 at 04:05
  • 1
    Code in a string can be executed with the `eval()` and `exec()` function. But you should know that many programmer will consider this an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern). – Klaus D. Dec 20 '20 at 04:11
  • As many people have raised this, I agree evaluating code that comes in a file has unimaginable potential for exploitation and is a major security hole. It would be good to reconsider design decisions and instead of storing code in a file, maybe store the parameters required to execute that code in the file and then use them(after proper validation, of course) in your code. – punter147 Dec 20 '20 at 04:50

1 Answers1

0

Ideally you should store only pattern in external file. For now we can extract the pattern from the command and use it here.

Code:

import re

list1 = ["guru99 get", "guru99 give", "guru Selenium"]
regex_string_in_file = 're.match("(g\w+)\W(g\w+)", element)'
pattern = regex_string_in_file.split('"')[1]
for element in list1:
     re.match(pattern, element)
     if z:
        print((z.groups()))
    
Aaj Kaal
  • 1,205
  • 1
  • 9
  • 8