नोट
import java.io.File;
def fileNames = [ "https://stackoverflow.com/a/b.c/first.txt",
"/b/c/second",
"c:\\a\\b.c\\third...",
"c:\\a\b\\c\\.text"
]
def fileSeparator = "";
fileNames.each {
// You can keep the below code outside of this loop. Since my example
// contains both windows and unix file structure, I am doing this inside the loop.
fileSeparator= "\\" + File.separator;
if (!it.contains(File.separator)) {
fileSeparator = "\\/"
}
println "File extension is : ${it.find(/((?<=\.)[^\.${fileSeparator}]+)$/)}"
it = it.replaceAll(/(\.([^\.${fileSeparator}]+)?)$/,"")
println "Filename is ${it}"
}
के लिए निम्न उपाय इस उदाहरण के लिए काम नहीं करता है (अपाचे लाइब्रेरी का उपयोग कर एक को छोड़कर) में से कुछ - c: /test.me/firstfile
अगर मैं कोशिश उपर्युक्त प्रविष्टि के लिए एक एक्सटेंशन खोजने के लिए, मुझे ".me/firstfile" मिलेगा: --(
उपस्थित होने पर फ़ाइल.सेपरेटर की आखिरी घटना को ढूंढने के लिए बेहतर तरीका होगा और फिर फ़ाइल नाम या एक्सटेंशन देखें।
नोट: (नीचे एक छोटी सी चाल होती है। विंडोज के लिए, फ़ाइल विभाजक \ है। लेकिन यह नियमित अभिव्यक्ति में एक विशेष चरित्र है और इसलिए जब हम नियमित अभिव्यक्ति में File.separator युक्त चर का उपयोग करते हैं, तो मुझे इसे बचाना होगा।
def fileSeparator= "\\" + File.separator;
आशा है कि यह बनाता है भावना :)
इस आजमाएं::
import java.io.File;
String strFilename = "C:\\first.1\\second.txt";
// Few other flavors
// strFilename = "/dd/dddd/2.dd/dio/dkljlds.dd"
def fileSeparator= "\\" + File.separator;
if (!strFilename.contains(File.separator)) {
fileSeparator = "\\/"
}
def fileExtension = "";
(strFilename =~ /((?<=\.)[^\.${fileSeparator}]+)$/).each { match, extension -> fileExtension = extension }
println "Extension is:$fileExtension"
स्रोत
2016-02-19 11:19:06
कभी कभी फ़ाइलें एक विस्तार नहीं है, लेकिन एक 'उन में .' की क्या ज़रूरत है। –