Lionel Thiry
10/14/2004 10:14:00 PM
Florian G. Pflug a écrit :
> Lionel Thiry wrote:
>
>> I'd like to make some kind of substitution like in a shell: "${var}".
>> For that purpose, I use this pattern: /\$\{(.*?)\}/.
>>
>> But I also want to be able to escape those special caracters $, { and
>> }. Examples:
>> "${var\\}weird}" # which is a variable with "var{weird" as name
>> "\\${var}" # which is the simple string "${var}" with no substitution
>
>
> Use: /(^|[^\\]|(\\\\)+)\$\{(([^\}\\]|(\\.))*)\}/
>
> I testes this with:
> puts
> (STDIN.readlines.join("\n").gsub(/(^|[^\\]|(\\\\)+)\$\{(([^\}\\]|(\\.))*)\}/m)
> {|m| "#{$1}--#{$3.gsub(/\\(.)/, "\\1")}--"})
> And it seems to work (replaces ${var} with --var--, but only if not
> escaped).
>
> The first part (/(^|[^\\]|(\\\\)+)/) basically means "either
> start-of-string, non-backslash, or an even amount of backslash".
> The part (/\{(([^\}\\]|(\\.))*)\}/) means "start with {, and than allow
> any number of groups that consist of either a sequence of non-} and
> non-\, or
> of an escaped character (/\\./).
>
> greetings, Florian Pflug
Thanks a lot for the help, but the pattern you gave is not perfect:
re = /(^|[^\\]|(\\\\)+)\$\{(([^\}\\]|(\\.))*)\}/
'pre${var}'.match # => prematch is "pr"
Lionel Thiry