Если вы уже знаете базовый формат и стиль содержимого основной строки, то вы можете использовать пользовательский метод поиска подстроки для получения нужных данных.Метод, который я предоставляю ниже, позволяет вам извлечь подстроку, содержащуюся между двумя другими подстроками, например:
Если вы хотите получить имя файла, связанное с подстрокой "filename =" (которая, конечно, является "mozilla".pdf "), тогда вы бы предоставили методу значение с левой строкой "filename=\""
и правой строкой "\""
.
Метод возвращает одномерный массив String всех вхождений, где может бытьподстрока между предоставленными подстрокой Left и Right, поэтому для примера выше мы бы назвали метод следующим образом:
String inputString = "Content-Type: application/pdf; name=\"mozilla.pdf\" "
+ "Content-Description: mozilla.pdf Content-Disposition: attachment; "
+ "filename=\"mozilla.pdf\"; size=92442; creation-date=\""
+ "Fri, 12 Oct 2018 14:14:00 GMT\"; modification-date=\""
+ "Fri, 12 Oct 2018 14:14:00 GMT\"Content-Transfer-Encoding: base64";
String[] fileNames = getSubstring(inputString,"filename=\"", "\"");
for (int i = 0; i < fileNames.length; i++) {
System.out.println("File Name " + (i+1) + ":\t" + fileNames[i]);
}
Это в конечном итоге выводит все имена файлов, найденные в основной строке ввода, в окно консоли.Если вам нужен только первый экземпляр имени файла, вы можете поместить индексное значение в конце вызова метода, чтобы получить нужное имя файла, например:
String fileName = getSubstring(inputString,"filename=\"", "\"")[0];
System.out.println("File Name:\t" + fileName);
. Это выведет: File Name: mozilla.pdf
в окно консоли.
Вот метод:
<code>/**
* Retrieves any string data located between the supplied string leftString
* parameter and the supplied string rightString parameter.<br><br>
*
* It can also retrieve a substring located at the beginning or the end of
* the main input string (see: leftString and rightString parameter information).
*
* <p>
* This method will return all instances of a substring located between the
* supplied Left String and the supplied Right String which may be found
* within the supplied Input String.<br>
*
* @param inputString (String) The string to look for substring(s) in.
*
* @param leftString (String) What may be to the Left side of the substring
* we want within the main input string. Sometimes the
* substring you want may be contained at the very beginning
* of a string and therefore there is no Left-String available.
* In this case you would simply pass a Null String ("") to
* this parameter which basically informs the method of this
* fact. Null can not be supplied and will ultimately generate
* a NullPointerException. If a Null String ("") is supplied
* then the rightString parameter <b>must</b> contain a String.
*
* @param rightString (String) What may be to the Right side of the
* substring we want within the main input string.
* Sometimes the substring you want may be contained
* at the very end of a string and therefore there is
* no Right-String available. In this case you would
* simply pass a Null String ("") to this parameter
* which basically informs the method of this fact.
* Null can not be supplied and will ultimately generate
* a NullPointerException. If a Null String ("") is supplied
* then the leftString parameter <b>must</b> contain a String.
*
* @param options (Optional - Boolean - 2 Parameters):<pre>
*
* ignoreLetterCase - Default is false. This option works against the
* string supplied within the leftString parameter
* and the string supplied within the rightString
* parameter. If set to true then letter case is
* ignored when searching for strings supplied in
* these two parameters. If left at default false
* then letter case is not ignored.
*
* trimFound - Default is true. By default this method will trim
* off leading and trailing white-spaces from found
* sub-string items. General sentences which obviously
* contain spaces will almost always give you a white-
* space within an extracted sub-string. By setting
* this parameter to false, leading and trailing white-
* spaces are not trimmed off before they are placed
* into the returned Array.
* * @return (1D String Array) Возвращает одномерный массив строк *, содержащий все подстроки, найденные в предоставленном Input *Строка, которая находится между поставляемой левой строкой и поставляемой * правой строкой.Возвращает Null, если ничего не найдено.* * Вы можете немного сократить этот метод, возвращая List * ArrayList и удаляя код преобразования 'List to 1D Array' в * конце этого метода.Этот метод изначально сохраняет свои выводы * в объекте List Interface.* / public static String [] getSubstring (String inputString, String leftString, String rightString, boolean ... options) {// Ничего не вернуть, если ничего не было предоставлено.if (inputString.equals ("") || (leftString.equals ("") && rightString.equals (""))) {return null;} // Готовим необязательные параметры, если таковые имеются.// Если ничего не указано, используйте Defaults ... boolean ignoreCase = false;// По умолчанию.логическое trimFound = true;// По умолчанию.if (options.length> 0) {if (options.length> = 1) {ignoreCase = options [0];} if (options.length> = 2) {trimFound = options [1];}} // Удаляем любые управляющие символы ASCII из // предоставленной строки (если они существуют).String modString = inputString.replaceAll ("\\ p {Cntrl}", "");// Установить объект массива List String для хранения // найденных подстрок между предоставленной левой // строкой и предоставленной правой строкой.List list = new ArrayList <> ();// Используем Pattern Matching, чтобы найти наши возможные подстроки в предоставленной Input String.Строка regEx = Pattern.quote (leftString) + (! RightString.equals ("")? "(. *?)": "(. *)?") + Pattern.quote (rightString);if (ignoreCase) {regEx = "(? i)" + regEx;} Pattern pattern = Pattern.compile (regEx);Matcher matcher = pattern.matcher (modString);while (matcher.find ()) {// Добавить найденные подстроки в список.Строка найдена = matcher.group (1);if (trimFound) {found = found.trim ();} list.add (найдено);} String [] res;// Преобразование ArrayList в 1D String Array.// Если список содержит что-то, тогда преобразуем if (list.size ()> 0) {res = new String [list.size ()];res = list.toArray (res);} // В противном случае вернуть Null.else {res = null;} // Возвращаем String Array.вернуть Res;}
Чтобы извлечь данные, содержащиеся в предоставленной строке:
System.out.println("Content-Type:\t\t\t" + getSubstring(inputString,"Content-Type:", ";")[0]);
System.out.println("Name:\t\t\t\t" + getSubstring(inputString,"name=\"", "\"")[0]);
System.out.println("Content-Description:\t\t" + getSubstring(inputString,"Content-Description:", "Content-Disposition:")[0]);
System.out.println("Content-Disposition:\t\t" + getSubstring(inputString,"Content-Disposition:", ";")[0]);
System.out.println("File Name:\t\t\t" + getSubstring(inputString,"filename=\"", "\"")[0]);
System.out.println("File Size:\t\t\t" + getSubstring(inputString,"size=", ";")[0]);
System.out.println("Creation Date:\t\t\t" + getSubstring(inputString,"creation-date=\"", "\";")[0]);
System.out.println("Modification Date:\t\t" + getSubstring(inputString,"modification-date=\"", "\"")[0]);
System.out.println("Content Transfer Encoding\t" + getSubstring(inputString,"Content-Transfer-Encoding:", "")[0]);
Вывод на консоль будет:
Content-Type: application/pdf
Name: mozilla.pdf
Content-Description: mozilla.pdf
Content-Disposition: attachment
File Name: mozilla.pdf
File Size: 92442
Creation Date: Fri, 12 Oct 2018 14:14:00 GMT
Modification Date: Fri, 12 Oct 2018 14:14:00 GMT
Content Transfer Encoding base64