-2

I need to write a regex matching pattern code to either return true if there is one '+' between two words and nothing else. I have written the code to check if there is only one '+' in the string but how will I check it is between two words? The code is below:

import re

inputStr= "ali+ahmedafaw+"
inputStr2= "hello+world+again"

plus=re.findall(r'[+]', inputStr)

print (plus)

l_plus=len(plus)
print "The length is ",l_plus

if l_plus<=1:
    print "True"
else:
    print "False"    
PRVS
  • 1,612
  • 4
  • 38
  • 75

1 Answers1

1

Actually it depends on what you mean by word. If you mean a word with more than one character, you can simply use [a-zA-Z]+ around the + character. Or other patterns which will match different characters like \w to match word characters.

re.search(r'[a-zA-Z]+\+[a-zA-Z]+', input_str) 

But if you just want it doesn't appears at the leading and trailing of your text you can use negative look-around:

re.search(r'(?<!^)\+(?!$)', input_str)
Mazdak
  • 105,000
  • 18
  • 159
  • 188