Home > OS >  Regex to capture the group
Regex to capture the group

Time:09-14

I have a text where I want to capture email with line starting from "Email: ******"

Details of Contact Made: 
Sender's Name: Test (Individual) 
Mobile: 4354354354 
Email: [email protected] 
Message: I am interested in your property. Please get in touch with me 
Click here 
<https://www.magicbricks.com/bricks/mailerautologin.html?

I have tried with .match(/Email\:(.*)\1/g)

But I am getting [Email:] instead of [email protected] How do I get the matching email from the group

CodePudding user response:

You need to access the first capture group. But I would use this version:

var text = `Details of Contact Made: 
Sender's Name: Test (Individual) 
Mobile: 4354354354 
Email: [email protected] 
Message: I am interested in your property. Please get in touch with me 
Click here 
<https://www.magicbricks.com/bricks/mailerautologin.html?`;

var email = text.match(/Email:\s*(\S ?@\S )/)[1];
console.log(email);

CodePudding user response:

This regex will get exactly what you want:

/(?<=Email: )(.*)/g

Please check https://regexr.com/6tuln

CodePudding user response:

The \1 part in the pattern should not be there, as it is a backreference to what is captured in group 1.

You get Email: as a result because an empty string it the only possibility to capture and refer to the same captured value with \1

You also don't have to escape the colon.


Possible fixes with a capture group are:

Email:(.*)
Email:\s*(. )
Email:\s*(\S )

Or the more specific ones:

Email:\s*([^\s@] @[^\s@] )
\bEmail:\s*([^\s@] @[^\s@] )(?!\S)

See a regex demo.

  • Related