rubyist
rubyist

Reputation: 3132

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": "[email protected]",
    "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);

Upvotes: 0

Views: 96

Answers (2)

Carsten Massmann
Carsten Massmann

Reputation: 28236

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": "[email protected]",
"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)

Upvotes: 0

antoinestv
antoinestv

Reputation: 3306

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": "[email protected]",
    "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

Upvotes: 2

Related Questions