2010-09-08 19 views
8

Sto cercando di creare un Regex Javascript che acquisisca il nome file senza l'estensione del file. Ho letto gli altri post qui e 'vai a questa pagina:http://gunblad3.blogspot.com/2008/05/uri-url-parsing.html' sembra essere la risposta predefinita. Questo non sembra fare il lavoro per me. Quindi ecco come sto cercando di far funzionare la regex:REGEX: Capture Nome file dall'URL senza estensione file

  1. Trova l'ultima barra "/" nella stringa dell'oggetto.
  2. Cattura tutto tra quella barra e il periodo successivo.

Il più vicino ho potuto ottenere era:. /([^ /] ) \ w $ Quale sulla corda 'http://example.com/index.htm' exec() sarebbe catturare /index.htm e indice.

Ho bisogno di questo per catturare solo indice.

risposta

39
var url = "http://example.com/index.htm"; 
var filename = url.match(/([^\/]+)(?=\.\w+$)/)[0]; 

Andiamo attraverso l'espressione regolare:

[^\/]+ # one or more character that isn't a slash 
(?=  # open a positive lookahead assertion 
    \.  # a literal dot character 
    \w+  # one or more word characters 
    $  # end of string boundary 
)   # end of the lookahead 

Questa espressione raccoglierà tutti i caratteri che non sono una barra che vengono immediatamente seguito (grazie allo lookahead) da un'estensione e dalla fine della stringa - o, in altre parole, tutto dopo l'ultima barra e fino all'estensione.

In alternativa, è possibile fare questo senza le espressioni regolari del tutto, trovando la posizione dell'ultimo / e l'ultimo . utilizzando lastIndexOf e ottenere un substring tra questi punti:

var url = "http://example.com/index.htm"; 
var filename = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf(".")); 
+1

Questa soluzione non riesce sui nomi di file con più periodi, se è necessario tale test, vedere la soluzione di @Berrerren. –

1

Si può provare questo regex:

([^/]*)\.[^.]*$ 
17

testato e funziona, anche per pagine senza estensione di file.

var re = /([\w\d_-]*)\.?[^\\\/]*$/i; 

var url = "http://stackoverflow.com/questions/3671522/regex-capture-filename-from-url-without-file-extention"; 
alert(url.match(re)[1]); // 'regex-capture-filename-from-url-without-file-extention' 

url = 'http://gunblad3.blogspot.com/2008/05/uri-url-parsing.html'; 
alert(url.match(re)[1]); // 'uri-url-parsing' 

([\w\d_-]*) ottenere una stringa contenente le lettere, le cifre, sottolineatura o trattini.
\.? forse la stringa è seguita da un punto.
[^\\\/]*$ ma certamente non seguito da una barra o un backslash fino alla fine.
/i oh si, ignorare il caso.

+0

Cattura anche nomi di file che hanno più periodi, la risposta accettata non riesce su quelli. (foo.global.js, ecc.). –

0

Non ho trovato nessuna risposta sufficientemente vicina. Ecco la mia soluzione.

function getFileName(url, includeExtension) { 
    var matches = url && typeof url.match === "function" && url.match(/\/?([^/.]*)\.?([^/]*)$/); 
    if (!matches) 
     return null; 

    if (includeExtension && matches.length > 2 && matches[2]) { 
     return matches.slice(1).join("."); 
    } 
    return matches[1]; 
} 

var url = "http://example.com/index.htm"; 
var filename = getFileName(url); 
// index 
filename = getFileName(url, true); 
// index.htm 

url = "index.htm"; 
filename = getFileName(url); 
// index 
filename = getFileName(url, true); 
// index.htm 

// BGerrissen's examples 
url = "http://stackoverflow.com/questions/3671522/regex-capture-filename-from-url-without-file-extention"; 
filename = getFileName(url); 
// regex-capture-filename-from-url-without-file-extention 
filename = getFileName(url, true); 
// regex-capture-filename-from-url-without-file-extention 

url = "http://gunblad3.blogspot.com/2008/05/uri-url-parsing.html"; 
filename = getFileName(url); 
// uri-url-parsing 
filename = getFileName(url, true); 
// uri-url-parsing.html 

// BGerrissen fails 
url = "http://gunblad3.blogspot.com/2008/05/uri%20url-parsing.html"; 
filename = getFileName(url); 
// uri%20url-parsing 
filename = getFileName(url, true); 
// uri%20url-parsing.html 

// George Pantazis multiple dots 
url = "http://gunblad3.blogspot.com/2008/05/foo.global.js"; 
filename = getFileName(url); 
// foo 
filename = getFileName(url, true); 
// foo.global.js 

// Fringe cases 
url = {}; 
filename = getFileName(url); 
// null 
url = null; 
filename = getFileName(url); 
// null 

Per adattarsi alla domanda iniziale, il comportamento predefinito è quello di escludere l'estensione, ma che può essere facilmente invertita.