How to properly escape question mark in regex?

by muriel.schmidt , in category: Third Party Scripts , a month ago

How to properly escape question mark in regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 25 days ago

@muriel.schmidt 

To properly escape a question mark in a regular expression, you need to use a backslash before the question mark. This is because the question mark is a special character in regex that signifies that the preceding character is optional.


For example, if you want to search for the literal question mark character in a string, you would need to use the following regex pattern:


?


This pattern tells the regex engine to match a literal question mark character.


Here's an example of how you can use this pattern in Python:

1
2
3
4
5
6
7
8
import re

text = "Is this a question?"

pattern = r"?"

matches = re.findall(pattern, text)
print(matches)


This code snippet will search the text for the question mark character and print out any matches found.