⊗pyPmRESHt 45 of 128 menu

Hat symbol inside sets in Python regular expressions

As you know, the hat inside [ ] negates when written at the beginning of brackets. So, it is a special symbol inside these brackets. To get the hat as a symbol, you need to either escape it or remove it from the first place.

Example

In the following example, the search pattern is: the first character is everything except 'd', then the two letters 'x':

txt = 'axx bxx ^xx dxx' res = re.sub('[^d]xx', '!', txt) print(res)

As a result, the following will be written to the variable:

'! ! ! dxx'

Example

Now the search template is: the first character is 'd' or '^', then two letters 'x':

txt = 'axx bxx ^xx dxx' res = re.sub('[d^]xx', '!', txt) print(res)

As a result, the following will be written to the variable:

'axx bxx ! !'

Example

You don't have to remove the header from the first place, but simply escape it with a backslash, and it will begin to denote itself:

txt = 'axx bxx ^xx dxx' res = re.sub('[\^d]xx', '!', txt) print(res)

As a result, the following will be written to the variable:

'axx bxx ! !'

Practical tasks

Given a string:

txt = '^xx axx ^zz bkk @ss'

Write a regular expression that will find lines according to the pattern: a hat or a dog, then two Latin letters.

Given a string:

txt = '^xx axx ^zz bkk @ss'

Write a regular expression that will find lines according to the pattern: NOT a hat and not a dog, and then two Latin letters.

Given a string:

txt = '^xx axx ^zz bkk'

Write a regular expression that will find lines according to the pattern: not a hat and not a space, and then two Latin letters.

enru