Normally a regular expression tries to gobble up as much as it can, in this case it will try to match the 'a' furthest away from 'foo'.
/a[^a]*foo/
This will match an 'a', any number of anything-but-a, then foo.
Alternatively:
/a.*?foo/
Here the ?
makes the regexp 'not greedy'. That is, it
will try to match across the minimum amount of characters (hence the
closest 'a' to 'foo').
Can you spot the falicy?