我對正則運算式很陌生,我想從 API 回應中提取一些資料。
我的 API 呼叫得到了回應:
{
server: 'nginx/1.21.0',
date: 'Mon, 25 Apr 2022 11:34:20 GMT',
'content-type': 'text/html; charset=UTF-8',
'transfer-encoding': 'chunked',
'x-powered-by': 'PHP/7.4.16',
expires: 'Sun, 19 Nov 1978 05:00:00 GMT',
'cache-control': 'no-store, no-cache, must-revalidate, max-stale=0, private, post-check=0, pre-check=0',
'x-content-type-options': 'nosniff',
'content-security-policy': "frame-ancestors 'self';",
'set-cookie': [
'SSESS8b04132f4690dc8ceb7837d5134a5519=ZbgVsmpp6DBRWwNCRMm5DTpfEoKffsNM7l8ILoCWkug; path=/; domain=test.net; secure; HttpOnly',
'su=1; expires=Thu, 22-Apr-2032 11:34:20 GMT; Max-Age=315360000; path=/; domain=test.net',
'lt=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; test.net',
'dtCookie=v_4_srv_10_sn_6364C36040ADFF47B91A838BB8B2CADD_perc_100000_ol_0_mul_1_app-3Aea7c4b59f27d43eb_1; Path=/; Domain=test.net',
'870be6fb89fc78ad2ca0eca3828e3019=7055c78f3c2b7311a5c77934caad6939; path=/; HttpOnly; Secure; SameSite=None'
],
'x-oneagent-js-injection': 'true',
'x-ruxit-js-agent': 'true',
'server-timing': 'dtSInfo;desc="0", dtRpid;desc="493206686"',
connection: 'close'
}
我想提取SSESS8b04132f4690dc8ceb7837d5134a5519和ZbgVsmpp6DBRWwNCRMm5DTpfEoKffsNM7l8ILoCWkug這些變數,并且每次運行都是不同的值。
我設法構建了一個捕獲整個鍵/值的組,但是當我嘗試控制它時,它仍然不起作用。
https://regex101.com/r/2dKW4s/1
嘗試1為:
var matches1 = loginModern.headers.match(new RegExp("(SSESS.*)=(. ?);\s*path"));
console.log(matches1[2]);
result output: TypeError: loginModern.headers.match is not a function
嘗試2:
const regex1 = new RegExp('(SSESS.*)=(. ?);\s*path');
var matches1 = regex1.exec(loginModern.headers)
console.log(matches1);
null
如何
從上述回應中獲取SSESS8b04132f4690dc8ceb7837d5134a5519& ,記住它們正在改變變數?ZbgVsmpp6DBRWwNCRMm5DTpfEoKffsNM7l8ILoCWkug
任何幫助表示贊賞
uj5u.com熱心網友回復:
沙盒:https ://codesandbox.io/s/jwdgmp
const setCookieArray = loginModern.headers["set-cookie"];
const stringContainingSSESS = setCookieArray.find((item) =>
item.includes("SSESS")
);
const matches = stringContainingSSESS.match(/(SSESS[a-zA-Z0-9]*)=(. ?);/);
console.log("key", matches[1]);
console.log("value", matches[2]);
我運行了你提供的正則運算式loginModern.headers,它有一些匹配的問題。這個正則運算式更準確
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/465828.html
標籤:javascript 正则表达式
上一篇:正則運算式在數字和單位之間添加下劃線(或在數字和單位之間用下劃線替換空格)
下一篇:匹配規則的模式
