簡體   English   中英

正則表達式:如何從Cookie字符串中提取JSESSIONID Cookie值?

[英]Regex: how to extract a JSESSIONID cookie value from cookie string?

我可能會收到以下cookie字符串。 hello=world;JSESSIONID=sdsfsf;Path=/ei

我需要提取JSESSIONID的值

我使用以下模式,但似乎不起作用。 但是https://regex101.com顯示它是正確的。

Pattern PATTERN_JSESSIONID = Pattern.compile(".*JSESSIONID=(?<target>[^;\\n]*)");

您可以使用正則表達式(^|;)JSESSIONID=(.*);通過更簡單的方法達到目標(^|;)JSESSIONID=(.*); 這是Regex101上的演示 (您忘記了使用保存按鈕鏈接正則表達式)。 看下面的代碼。 您必須使用Matcher類提取匹配的值:

String cookie = "hello=world;JSESSIONID=sdsfsf;Path=/ei";
Pattern PATTERN_JSESSIONID = Pattern.compile("(^|;)JSESSIONID=(.*);");
Matcher m = PATTERN_JSESSIONID.matcher(cookie);
if (m.find()) {
   System.out.println(m.group(0));
}

產值:

sdsfsf

當然,結果取決於輸入文本的所有可能變化。 上面的代碼段將在每種情況下都起作用,該值介於JSESSIONID;之間; 字符。

您可以在正則表達式下面嘗試:

JSESSIONID=([^;]+)

正則表達式說明

String cookies = "hello=world;JSESSIONID=sdsfsf;Path=/ei;submit=true";
Pattern pat = Pattern.compile("\\bJSESSIONID=([^;]+)");
Matcher matcher = pat.matcher(cookies);
boolean found = matcher.find();
System.out.println("Sesssion ID: " + (found ? matcher.group(1): "not found"));

演示

您甚至還可以通過分割和替換字符串來達到您的目標,下面我分享了對我有用的。

String s = "hello=world;JSESSIONID=sdsfsf;Path=/ei";

List<String> sarray = Arrays.asList(s.split(";"));

String filterStr = sarray.get(sarray.indexOf("JSESSIONID=sdsfsf"));
System.out.println(filterStr.replace("JSESSIONID=", ""));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM