This looks correct to me, but it's complex enough that it seems like it would be easy and worthwhile to create a number of unit tests just to make sure the regexp returned by this function is doing what you expect.