![](/img/trans.png)
[英]How do you extract the JSESSIONID cookie from an XHR request in Dojo?
[英]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.