I have the following string:
var text = "Meu nome <[email protected]>";
I would like to only get [email protected]
, using Regex.
I have the following string:
var text = "Meu nome <[email protected]>";
I would like to only get [email protected]
, using Regex.
Using the Javascript regex API:
var text = "Meu nome <[email protected]>";
var regex = /(<)(.*)(>)/;
console.log(regex.exec(text)[2]);
//
delimits the area to execute a regex (<)
looks for a string that begins with <
(.*)
Any character within <
This regex will return a result of three groups, so the (>)
, which will only get the email .
You can do this:
var text = "Meu nome <[email protected]>";
var email = text.replace(/.*<(.*)>.*/, '$1');
console.log(email);
Note that $ 1 represents (.*)
, between <
and >
, which in this case is email.
You can find more information about regex here .
The ideal for these cases is to think as much of the information as possible that will generate a catch pattern.
You said you want what's between <
and >
@
and which special characters will be valid, eg _-.
>
itself? (his final character). e.g. <var1 > var2>
As I do not know exactly what your catch is I'll consider the ones I quoted above.
/<([a-z]+@[a-z]+(\.[a-z]{2,3}){1,2})>/i
. REGEX101 ** >
(final char): /<([^>]+)>/
. REGEX101
>
in the middle: /<(.*)>/
. REGEX101
All the results you want are in group 1.
**: reminding you that you can add special characters to parts of [
... ]
. ex. [a-z_-.]
If you want to capture several at a time, you just need to flag g
at the end of the regex.
var text ="Meu nome <[email protected]>";
var r = /<([^>]+)>/
console.log(r.exec(text)[1])
I know the question is already answered, but what if I wanted to get more than one email? These regular expressions are only working for an email.
I have done the function below, which although it does not use regular expressions, has the functionality of locating and saving content between <
and >
of one or more occurrences.
<script>
var texto = "Meus emails são <[email protected]>,<[email protected]> e <[email protected]>";
// Função que localiza conteúdo(emails) entre < e > e guarda em array
function localizar_tags(texto)
{
var emails = new Array();
i = 0;
while(texto.search("<") != -1)
{
pos_inicio = texto.search("<");
pos_fim = texto.search(">");
email = texto.substring(pos_inicio+1, pos_fim);
emails[i]=email;
texto = texto.substring(pos_fim+1,texto.length);
i++;
}
return emails;
}
// Para testar a função
window.onload=function()
{
emails = localizar_tags(texto);
for(i=0;i<emails.length;i++)
{
console.log(emails[i]);
}
}
</script>