2016-04-12 3 views
1

Я пытаюсь извлечь ссылку, которая говорит 'rel = "next"' из строки ниже. Проблема в том, что порядок четырех может измениться, в зависимости от того, существует ли ссылка на «предыдущий» или «следующий». Таким образом, я не могу использовать Regex или разбивать на массив строк и надежно получить ссылку.Как извлечь данные скобки из строки

Вот строка:

<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=0&per_page=100>; rel="first",<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=20&per_page=100>; rel="last",<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=1&per_page=100>; rel="next" 

И мне нужно, чтобы получить эту строку:

<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=1&per_page=100>; rel="next" 

Вот читаемая версия:

<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=0&per_page=100>; rel="first", 
<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=20&per_page=100>; rel="last", 
<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=1&per_page=100>; rel="next" 

И в конечном итоге извлечь только ссылку для Запрос API. Я попытался разделить массив на ,, однако URL-адрес может содержать ,, что также ненадежно. Спасибо!

+3

Не могли бы вы прояснить ситуацию? Что вы пытаетесь сделать точно? – Maljam

+0

Я думаю, вы можете использовать 'find' с [lookahead] (http://www.regular-expressions.info/lookaround.html), если все разделены запятой, как в этой демонстрации, в regex101: [' <[^>] +> (? = [^,] *? отн = "следующий)'] (https://regex101.com/r/gZ7iV0/2) –

ответ

1
String myString = "<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=0&per_page=100>; rel=\"first\",<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=20&per_page=100>; rel=\"last\",<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=1&per_page=100>; rel=\"next\""; 
    try { 
    Pattern regex = Pattern.compile("\"last\",(.*?)$"); 
    Matcher regexMatcher = regex.matcher(myString); 
    if(regexMatcher.find()) { 
     String next = regexMatcher.group(1); 
     System.out.println(next); 
    } 
    } catch (PatternSyntaxException ex) { 
    // Syntax error in the regular expression 
    } 

//<http://v4-api.prod.emailanalyst.com/v4/competitive/search?Authorization={API_KEY}&mobileReady=true&qd=between:20150101000000,20150101060000&onlyCommercial=true&hasCreative=true&page=1&per_page=100>; rel="next" 

REGEX ОБЪЯСНЕНИЕ:

"last",(.*?)$ 

Options: Case sensitive; Exact spacing; Dot doesn’t match line breaks; ^$ don’t match at line breaks; Greedy quantifiers 

Match the character string “"last",” literally (case sensitive) «"last",» 
Match the regex below and capture its match into backreference number 1 «(.*?)» 
    Match any single character that is NOT a line break character (line feed) «.*?» 
     Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?» 
Assert position at the end of the string, or before the line break at the end of the string, if any (line feed) «$» 

DEMO: http://ideone.com/7mITYJ

0

Предполагая, что элементы всегда начинаются с "<http:", вы могли бы использовать регулярное выражение с положительным опережающего просмотра:

String[] elements = str.split(",(?=<http:)"); 
Смежные вопросы