Regular expressions using variables

Sorry, a stupid post, but i dont seem to be able to get a vairbale into a regular expression:
I am trying to get a foreign key from an email to address buy removing the number immediately before a specific domain in the to address

This works fine

var recip='1023@4expertsolutions.co.uk'
var casenum=utils.stringToNumber(recip.replace(/(^|.*\D+)(\d+)@4expertsolutions.*/,"$2"))

but i am being very thick and dont seem to find the right combination of " ’ ' " to get the variable into the expression!
This or any other combination i try doesn’t work.

var domain='@4expertsolutions.'
var recip='1023@4expertsolutions.co.uk'
var casenum=utils.stringToNumber(recip.replace(/(^|.*\D+)(\d+)"+domain+".*/,"$2"))

I really hate regular expressions. Its about time i attended a Marcel masterclass on them!

Thanks

David

If you want to use variables in a regexp, you need to use the RegExp constructor: ```
new RegExp(“pattern”);


For your code this will look like this:

var domain = ‘@4expertsolutions’;
var recip = ‘1023@4expertsolutions.co.uk’;
var regexp = new RegExp(“(^|.\D+)(\d+)" +domain+ ".”);
var casenum = utils.stringToNumber(recip.replace(regexp,“$2”));


Note that the "\" should be escaped when defining the regexp.

Easy, right? Regular expressions are awesome! <img src="{SMILIES_PATH}/icon_wink.gif" alt=";)" title="Wink" />

BTW, [here](http://www.javascriptkit.com/javatutors/re.shtml) is a nice (and short!) regexp tutorial.

Many thanks Jaos,

its easy when you know how! I used to have a fair grip of them in Perl many years ago, but have never got the formatting quite right in Servoy.

Anyway now i have a good working example! i found one error in my expression though, it needs to be d* not d+ else and email without a number in front of the address will pick the 4 from after the @ and also any number before, if someone has copied the email to another address with a number in it!

var regexp = new RegExp(“(^|.\D+)(\d)” +domain+ “.*”);

seems to get the case number for me.

Thanks again for the guiding hand

David