简体   繁体   中英

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

I have a string like below. 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  }"

I need to get userID and Mail from the above using regex. How can I achieve it. I tried with below regex code but didnt find luck.

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

As the string looks like a JSON document, instead of trying to build a regexp to extract the email you should probably just parse the JSON with JSON.parse(// ... .

The problem is that your string is not a valid JSON document but if the format won't change you can probably do something like that:

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

After carving out the valid JSON portion from the string you can parse it and access the properties you need:

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM