How can I match a text with colon using regex?

Question:

I want to use regex to match any case with only 1 colon in front of a name or behind it, but not a name in between two colons.

Matches things like this:

name: | :name | name:`asdf`

But should not match any of these:

:name: 
eman: 
nnamee: 
:nameasdfj

I have a regex that I think covers all cases for the first three, but it also matches :name: which I don’t want:

((?:^|W)name:(?:$|W))|((?:^|W):name(?:$|W))
Asked By: user1094771

||

Answers:

Try (?<!S)name:|:name(?!S)

demo

or slight boundry use (?<![a-z:])name:|:name(?![a-z:])

demo2


code sample using second regex

>>> import re
>>> regex = r'(?<![a-z:])name:|:name(?![a-z:])'
>>> content = 'asdf- name:'
>>> re.search(regex, content).group(0)
'name:'
Answered By: user13469682
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.