Python regular expression question.

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

Each variable has a string and I want to combine them and compile them into regular expressions. This is the case below.

import re

a = "[Question]"
b = "[Answer]"
c = "(Solution)"

message = "[Question] I'm curious about the regular expression.[Answer]"

regex = re.compile(f"{a}{b}{c}")

print(regex.sub("@", message)) # <= Invalid result
# Result 1: [Question] (Solution) I'm curious about the regular expression.[Answer]

If you execute it, you will get the results as above. It hasn't been changed at all. Actually, I want the results I want to come out as follows.

abc = re.compile(r'\[Question]|\[Answer]|\(Resolve\')
print(abc.sub("@", message)) # <= The result I want
# Result #2: @@ I'm curious about the regular [email protected]

How do I compile a regular expression of itself by assigning variables as one string?

regex python

2022-09-20 15:41

1 Answers

import re

a = "\\[Question\]"
b = "\\[Answer\\]"
c = "\\(Solution\\)"

message = "[Question] I'm curious about the regular expression.[Answer]"

regex = re.compile(f"{a}|{b}|{c}")

print(regex.sub("@", message)) # <= Invalid result
# Result 1: [Question] (Solution) I'm curious about the regular expression.[Answer]

abc = re.compile(r'\[Question]|\[Answer]|\(Resolve\')
print(abc.sub("@", message)) # <= The result I want
# Result #2: @@ I'm curious about the regular [email protected]

# # result
@@ I'm curious about the regular [email protected]
@@ I'm curious about the regular [email protected]


2022-09-20 15:41

If you have any answers or tips


© 2022 pinfo. All rights reserved.