Pascal
Pascal

Reputation: 2214

Regex: only matching if character occurs 1 time

I need to create a regex which finds the following pattern:

= Head: Some text =

I tried this:

^(?:[=]).*(?:[=])

But it also matches this (which it should not match):

== Hello Text 2 ==

So how can I tell regex not to match to multiple occurrence of ==

thanks for your answer.

Upvotes: 0

Views: 746

Answers (2)

stema
stema

Reputation: 92976

You can use a negated character class instead of .

^=[^=]*=$

[^=]* is matching any character, but "="

$ is matching the end of the string

See it here on Regexr

Upvotes: 2

Jon Clements
Jon Clements

Reputation: 142106

The following is fairly readable:

>>> s = '= Head: Some text ='
>>> t = '== Hello Text 2 =='
>>> re.match(r'=[ ](.*?)[ ]=', s).group(1)
'Head: Some text'
>>> re.match(r'=[ ](.*?)[ ]=', t).group(1)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    re.match(r'=[ ](.*?)[ ]=', t).group(1)
AttributeError: 'NoneType' object has no attribute 'group'

Upvotes: 2

Related Questions