Home > Software design >  How to properly escape question mark in regex?
How to properly escape question mark in regex?

Time:09-16

I have regex below that should detect interrogative sentence. But the problem is it does not include the question mark when I test it in regexr.com

Someone knows what is missing? thanks


Here's my regex (i tried to use double backlash but still not work):

\bWhat’s up\\?\b

Tested string: "Subject: What’s up? Christie"

Here's regexr: enter image description here

CodePudding user response:

Two issues:

Firstly to escape a ? character, you only need a single backslash. Two backslashes will match a literal \ character. (MDN: Character Classes)

Secondly, a ? is not a word character. \b matches the boundary between a word and a non-word character: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Assertions

  • Related