2010-07-13 5 views

risposta

3

Ksh:

$ s='abc/def/ghi' 
$ echo ${s%%/*} 
abc 
$ echo ${s%/*} 
abc/def 
$ echo ${s#*/} 
def/ghi 
$ echo ${s##*/} 
ghi 

Python:

>>> s='abc/def/ghi' 
>>> print s[:s.find("/")] 
abc 
>>> print s[:s.rfind("/")] 
abc/def 
>>> print s[s.find("/")+1:] 
def/ghi 
>>> print s[s.rfind("/")+1:] 
ghi 

Edit:

Per gestire il caso in cui il modello è mancante, come sottolineato da ΤΖΩΤΖΙΟΥ:

>>> s='abc/def/ghi' 
>>> t='no slash here' 
>>> print s[:s.find("/") % (len(s) + 1)] 
abc 
>>> print t[:t.find("/") % (len(t) + 1)] 
no slash here 
>>> print s[:s.rfind("/") % (len(s) + 1)] 
abc/def 
>>> print t[:t.rfind("/") % (len(t) + 1)] 
no slash here 
>>> print s[s.find("/")+1:] 
def/ghi 
>>> print t[t.find("/")+1:] 
no slash here 
>>> print s[s.rfind("/")+1:] 
ghi 
>>> print t[t.rfind("/")+1:] 
no slash here 
+0

Le soluzioni di ricerca sono difettose nel caso in cui la stringa di input non abbia il pattern; in questo caso, il carattere "/". 's =" nessuna barra qui "; print s [: s.find ("/")], s [: s.rfind ("/")] '. Se lo aggiusti, rimuoverò felicemente il mio downvote. – tzot

+0

@ ΤΖΩΤΖΙΟΥ: Ho aggiornato la mia risposta. –

2
${name##*/} 

è equivalente a:

re.match(".*?([^/]*)$")[1] 

${name%/*} 

è equivalente a:

re.match("(.*?)[^/]*$")[1] 
2

Non c'è status speciale per "strip a sinistra", "strip a destra ", ecc. Il metodo generale è re.sub - per exa mple, a "togliere tutto fino all'ultimo barra incluso" ("a sinistra", come ksh concettualizza esso):

name = re.sub(r'(.*/)(.*)', r'\2', name) 

e mettere a nudo "l'ultimo slash e tutto dopo" ("a destra" per ksh):

name = re.sub(r'(.*)/.*', r'\1', name) 

Questi partita il più possibile perché il * nei modelli RE è avida; utilizzare invece *? per la corrispondenza non avida ("il meno possibile").

1
>>> def strip_upto_max(astring, pattern): 
    "${astring##*pattern}" 
    return astring.rpartition(pattern)[2] 
>>> def strip_from_max(astring, pattern): 
    "${astring%%pattern*}" 
    return astring.partition(pattern)[0] 
>>> def strip_upto(astring, pattern): 
    "${astring#*pattern}" 
    return astring.partition(pattern)[2] 
>>> def strip_from(astring, pattern): 
    "${astring%pattern*}" 
    return astring.rpartition(pattern)[0] 

>>> strip_from("hello there", " t") 
'hello' 
>>> strip_upto("hello there", " t") 
'here' 

>>> text= "left/middle/right" 
>>> strip_from(text, "/") 
'left/middle' 
>>> strip_upto(text, "/") 
'middle/right' 
>>> strip_upto_max(text, "/") 
'right' 
>>> strip_from_max(text, "/") 
'left' 

Ma se la vostra intenzione è quella di utilizzare con i percorsi, verificare se le funzioni os.path.dirname (${name%/*}) e os.path.basename (${name##*/}) hanno le funzionalità desiderate.

Problemi correlati