benjohn / fysh.org wrote:

> Is there a regexp feature that lets me require something to be present
> in the input string for the regexp to match, but for that to not become
> captured as part of the match?

Neither yes nor no, because of how you have worded your question. Se below.

> I want this so that I can scan and gsub on a string of code and replace
> variables. Matching just variables requires looking at the context
> arround them, but if I capture this, I replace the context too.
> 
> Eg, to scan for variables called x or y, I might use:
>   /(^|[^a-zA-Z])[xy]([^a-zA-Z]|$)/
> 
> but using that on "exp(x)" will match (and replace) "(x)", which I don't
> want at all.

There are a number of ways to accomplish this. The simplest is to put the
part you want to preserve in parentheses, and refer to it in the
replacement.

Like this:

data.sub!(%r{(^|[^a-zA-Z])([xy])([^a-zA-Z]|$)},"\\1\\2\\3")

Notice about this example that the [xy] character class is now captured and
used as part of the replacement, so its original value is preserved.

Using this approach, you preserve the parts you don't want to replace, and
replace the parts you do. In the above example, everything is preserved,
but it is just meant to show the pattern.

-- 
Paul Lutus
http://www.arachnoid.com