Regex to capture the group

Viewed 36

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: 7c92e312-93d5-4354354-45435435@email.webhook.site 
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 7c92e312-93d5-4354354-45435435@email.webhook.site How do I get the matching email from the group

3 Answers

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: 7c92e312-93d5-4354354-45435435@email.webhook.site 
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);

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