[SOLVED] Regex to detect string including special characters


I have these inputs:

s1 = 'I am using c++ programming'. 

s2 = = 'I am usingc++ programming'. 

I want to check if s1 or s2 contains the exact word c++.

running this regex on both s1 and s2, it does not give any output:

x=s1 #x=s2

if re.search(r'\bc\+\+\b', x):

expected result: detect c++ in s1


You may use this regex for this using different flavors of word boundaries:


RegEx Demo

RegEx Details:

  • \b: Word boundary between a non-word and word character
  • c\+\+: Match c++
  • \B: Inverse of word boundary to match where \b doesn’t match

Python Code:

>>> import re
>>> s1 = 'I am using c++ programming'
>>> s2 = 'I am usingc++ programming'
>>> rx = re.compile(r'\bc\+\+\B')
>>> print (rx.findall(s1))
>>> print (rx.findall(s2))

Answered By – anubhava

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *