簡體   English   中英

正則表達式匹配字符串並在javascript中提取電子郵件和用戶名

[英]regex to match the string and extract email and user name in javascript

我有一個像下面這樣的字符串。 const myString =

"{
    "typ": "JWT",
    "alg": "44555"
}
{
    "XForwardedFor": "12.134.234.22",
    "sm_AppId": "test",
    "UserId": "changu",
    "sm_Userdn": "some userdn",
    "Mail": "changu@gmail.com",
    "DomainName": "www.test.com",
    "UserAgent": "Amazon",
    "CreationTime": "2020-09-08T05:01:55.616Z"
}
ii( NJm)'d=IXp:$uG\mf  }"

我需要使用正則表達式從上面獲取用戶 ID 和郵件。 我怎樣才能實現它。 我嘗試了下面的正則表達式代碼,但沒有找到運氣。

myString.match(/"UserId":"([\s\S]*?)"/i);

由於字符串看起來像一個 JSON 文檔,而不是嘗試構建一個正則表達式來提取電子郵件,您可能應該使用JSON.parse(// ... .

問題是您的字符串不是有效的 JSON 文檔,但如果格式不會改變,您可能可以執行以下操作:

const myString = `{
    "typ": "JWT",
    "alg": "44555"
}
{
    "XForwardedFor": "12.134.234.22",
    "sm_AppId": "test",
    "UserId": "changu",
    "sm_Userdn": "some userdn",
    "Mail": "changu@gmail.com",
    "DomainName": "www.test.com",
    "UserAgent": "Amazon",
    "CreationTime": "2020-09-08T05:01:55.616Z"
}
ii( NJm)'d=IXp:$uG\mf  }`
const regexp = /\{[^\}]*\}/gs
const email = JSON.stringify(myString.match(regexp)[1]).Mail

從字符串中提取出有效的 JSON 部分后,您可以解析它並訪問您需要的屬性:

 const resp=`{ "typ": "JWT", "alg": "44555" } { "XForwardedFor": "12.134.234.22", "sm_AppId": "test", "UserId": "changu", "sm_Userdn": "some userdn", "Mail": "changu@gmail.com", "DomainName": "www.test.com", "UserAgent": "Amazon", "CreationTime": "2020-09-08T05:01:55.616Z" } ii( NJm)'d=IXp:$uG\\mf }` let obj=JSON.parse(resp.match(/\\{[^{]*UserId[^}]*\\}/)) console.log(obj.UserId, obj.Mail)

暫無
暫無

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

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