How to properly escape question mark in regex?

by muriel.schmidt , in category: Third Party Scripts , 6 months ago

How to properly escape question mark in regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 6 months 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.

Related Threads:

How to add question mark to .htaccess?
How to escape a certain word in a url with google analytics regex?
How to properly compare bigint column in mysql 5.7?
How to mark a file as not binary in git?
How to mark documents as marked/deleted in mongodb?
How to escape quotes in PHP?