'How to transform embeded variables with optional indexing?

For an input text, I want to treat strings matching #^[_A-Za-z][_A-Za-z0-9]+ (e.g., #var) as variables and convert it to <varname>[i], where <varname> is the part matching [_A-Za-z][_A-Za-z0-9]+.

However, there can be also suffixes associated with varnames #^[_A-Za-z][_A-Za-z0-9]+.-?[0-9]+ (e.g, #var.-3, #var.4). For those, I want to transform them to things like var[i-3] and var[i+4]. Note that #var.-3 takes a higher precedence than #var, meaning #var.-3 should be matched first although #var can match whenever #var.-3 can match.

How to make this text transform using python?

Example input:

print #var, #var2.-3, #var3.4

Example output:

print var[i], var2[i-3], var3[i+4]

When you run ./program.py <<< 'print #var, #var2.-3, #var3.4' in command line, it should print print var[i], var2[i-3], var3[i+4].



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source