Python regular expression question.

Asked 2 years ago, Updated 2 years ago, 60 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 expression.@

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 expression.@

# # result
@@ I'm curious about the regular expression.@
@@ I'm curious about the regular expression.@


2022-09-20 15:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.