Reputation: 55
I am trying to create an expression that will give me an output of yes for strings, 6,7,8 and an output of no for 9 & 10. Any advice would be greatly appreciated!
#The regular expression is ' ^<[^<>]*>$ '
print ( 'The regular expression used for 5 strings was "^<[^<>]*>$"' )
string6 = '<an xml tag>'
string7 = '<an xml tag>, </closetag>'
string8 = '<with attribute="77">'
string9 = '<opentag><closetag>'
string10 = '</closetag>'
if re.search( r'^<[^<>]*,>$',string6 ) :
print( "yes" )
else:
print("no")
if re.search( r'^<[^<>]*,>$',string7 ) :
print( "yes" )
else:
print("no")
if re.search(r'^<[^<>]*>$',string8):
print("yes")
else:
print("no")
if re.search(r'^<[^<>]*>$',string9):
print("yes")
else:
print("no")
if re.search(r'^<[^<>]*>$',string10):
print("yes")
else:
print("no")
This is the result: yes no yes no yes
I am trying to get: yes yes yes no no
Upvotes: 0
Views: 60
Reputation: 20269
The first 3 strings have at least one space character in them and the last 2 don't. If you use a regular expression that's just a single space character, , it will match the first three and not the last two.
string6 = '<an xml tag>'
string7 = '<an xml tag>, </closetag>'
string8 = '<with attribute="77">'
string9 = '<opentag><closetag>'
string10 = '</closetag>'
if re.search( r' ',string6 ) :
print( "yes" )
else:
print("no")
if re.search( r' ',string7 ) :
print( "yes" )
else:
print("no")
if re.search(r' ',string8):
print("yes")
else:
print("no")
if re.search(r' ',string9):
print("yes")
else:
print("no")
if re.search(r' ',string10):
print("yes")
else:
print("no")
Upvotes: 1
Reputation: 782653
If you just have to match those specific strings, just use a regular expression with literal text in an alternation.
regex = r'^(?:<an xml tag>|<an xml tag>, </closetag>|<with attribute="77">)$';
for s in [string6, string7, string8, string9, string10]:
if (re.search(regex, s)):
print("yes")
else:
print("no")
It's not clear from the question what more general pattern could be used.
Upvotes: 1