Use this
^$|^(aboutus|race|cruise|westerlies|weather|reach|gear)/$
Вопрос
I want to match and group any of these listed words:
aboutus/
,race/
,cruise/
,westerlies/
,weather/
,reach/
,gear/
or empty_string
Here is a solution, but which will not match the empty_string:
^(aboutus|race|cruise|westerlies|weather|reach|gear)/$
So my question is: How to include Empty string in this matching?
I still don't get a good solution for this.
So I added one more regex specially for empty_string:ie ^$
.
Note: these regular expression is for django urls.py
.
update: It will be better if the capturing group does not contain /
Решение 2
Use this
^$|^(aboutus|race|cruise|westerlies|weather|reach|gear)/$
Другие советы
try this:
^(aboutus|race|cruise|westerlies|weather|reach|gear)?/$
edit: if '/' is in every case except the empty string try this
^((aboutus|race|cruise|westerlies|weather|reach|gear)(/))?$
You can make the capturing group optional:
^(aboutus|race|cruise|westerlies|weather|reach|gear)?/$
import re
rgx = re.compile('^((aboutus|race|cruise|westerlies'
'|weather|reach|gear)/|)$')
# or
li = ['aboutus','race','cruise','westerlies',
'weather','reach','gear']
rgx = re.compile('^((%s)/|)$' % '|'.join(li))
for s in ('aboutus/',
'westerlies/',
'westerlies/ ',
''):
m = rgx.search(s)
print '%-21r%r' % (s,rgx.search(s).group() if m else m)
result
'aboutus/' 'aboutus/'
'westerlies/' 'westerlies/'
'westerlies/ ' None
'' ''