views:

98

answers:

1

I am trying to use an HTML form and javascript (i mention this, because some advanced features of regex processing are not available when using it on javascript) to acomplish the following:

feed the form some text, and use a regex to look into it and "capture" certain parts of it to be used as variables...

i.e. the text is:

"abcde email: [email protected] email: [email protected] sdfsdaf..."

... now, my problem is that I cannot think of an elegant way of capturing both emails as the variables e1 and e2, for example.

the regex I have so far is something like this: /email: (\b\w+\b)/g but for some reason, this is not giving back the 2 matches... it only gives back [email protected] ><

sugestions?

+3  A: 

You can use RegExp.exec() to repeatedly apply a regex to a string, returning a new match each time:

var entry = "[...]"; //Whatever your data entry is
var regex = /email: (\b\w+\b)/g
var emails = []
while ((match = regex.exec(entry))) {
    emails[emails.length] = match[1];
}

I stored all the e-mails in an array (so as to make this work far arbitrary input). It looks like your regex might be a little off, too; you'll have to change it if you just want to capture the full e-mail.

Daniel Lew
Thanks. Yeah, my regex might be a little off, since i wanted to capture the addresses by using the parethesis... but your answer really helps
EroSan
+1 for mentioning this.... RegExp objects have state?! EWWWWWWW!!!!!
Jason S