Reputation:
I am trying to write a regrex expression that checks if certain characters & and @ appear at the start and end of the string.
This is what I have so far:
import re
def check_operators(inputstr):
return bool(re.search(r'^[&@]|[&@]^', inputstr))
print(check_operators("25 &")) #code outputs False
print(check_operators("& 25")) #code outputs True
print(check_operators(" & 25")) #code outputs False
All three of the outputs should be "True" because it should find those characters at the start and end of the string, but my code doesn't seem to be working. Any ideas?
Upvotes: 1
Views: 63
Reputation: 626950
You may use
def check_operators(string1):
return bool(re.search(r'^\s*[&@]|[&@]\s*$', string1))
See the Python demo
Details
^\s*[&@]
- start of string, 0+ whitespaces, &
or @
|
- or[&@]\s*$
- &
or @
, 0+ whitespaces, end of string.Upvotes: 1