Reputation: 1810
I'm using python and trying to write a regular expression that matches a hyphen (-) if it is not preceded by a period (.) and not followed by one character and a period.
This one is matching hyphen not preceded by a period and not followed by a character:
r'(?<!\.)(-(?![a-zA-Z]))'
Nothing I've tried seems to get me the right match for the negative look-ahead part (single character and period).
Any help appreciated. Even a totally different regex if I'm barking up the wrong tree altogether.
Edit
Thanks for the answers. I did actually try
r'(?<!\.)(-(?![a-zA-Z]\.))'
But I now realise that my logic was wrong, not my expression.
I've chosen the answer and upvoted the other correct ones :)
Upvotes: 1
Views: 1018
Reputation: 27585
import re
ss = ' a-bc1 d-e.2 .-gh3 .-N.4'
print 'The analysed string:\n',ss
print '\n(?!\.-[a-zA-Z]\.)'
print 'NOT (preceded by a dot AND followed by character-and-dot)'
r = re.compile('(?!\.-[a-zA-Z]\.).-...')
print r.findall(ss)
print '\n(?<!\.)-(?![a-zA-Z]\.)'
print 'NOT (preceded by a dot OR followed by character-and-dot)'
q = re.compile('.(?<!\.)-(?![a-zA-Z]\.)...')
print q.findall(ss)
result
The analysed string:
a-bc1 d-e.2 .-gh3 .-N.4
(?!\.-[a-zA-Z]\.)
NOT (preceded by a dot AND followed by character-and-dot)
['a-bc1', 'd-e.2', '.-gh3']
(?<!\.)-(?![a-zA-Z]\.)
NOT (preceded by a dot OR followed by character-and-dot)
['a-bc1']
Which case do you want in fact ?
Upvotes: 1
Reputation: 11601
Assuming that by "character" you mean (and I base this assumption on your example and on @SimonO101's comment) [A-Za-z]
, I think you are looking for something like this:
>>> r = re.compile(r'(?<!\.)-(?![A-Za-z]\.)')
>>> r.search('k.-kj')
>>> r.search('k-l.')
>>> r.search('k-ll')
<_sre.SRE_Match object at 0x02D46758>
>>> r.search('k-.l')
<_sre.SRE_Match object at 0x02D46720>
>>> r.search('l-..')
<_sre.SRE_Match object at 0x02D46758>
There is no need to try to enclose the hyphen in a group that also captures the negative lookahead assertion. Trying to do this only complicates the matter.
Upvotes: 3