Created
October 25, 2012 11:53
-
-
Save saltnlight5/3952178 to your computer and use it in GitHub Desktop.
varsubstitution.groovy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// String variable substitutions | |
def parseVariableNames(String text) { | |
def names = [] | |
def pos = 0, max = text.length() | |
while (pos < max) { | |
pos = text.indexOf('${', pos) | |
if (pos == -1) | |
break | |
def end = text.indexOf('}', pos + 2) | |
if (end == -1) | |
break | |
def name = text.substring(pos + 2, end) | |
names.add(name) | |
pos = end + 1 | |
} | |
return names | |
} | |
def replaceVariable(String key, String value, String text) { | |
//println "DEBUG: Replacing '${key}'' with '${value}'" | |
result = text.replaceAll('\\$\\{' + key + '}', value) | |
return result | |
} | |
// Test | |
def map = ["name": "Zemian", "id": "1001"] | |
def inputs = [ | |
'Hello ${name}', | |
'My id is ${id}', | |
'${name} is a good programmer.', | |
'${name}\'s id is ${id}.' | |
] | |
result = inputs.collect{ line -> | |
def names = parseVariableNames(line) | |
names.each{ key -> | |
line = replaceVariable(key, map.get(key), line) | |
} | |
line | |
} | |
assert result == [ | |
'Hello Zemian', | |
'My id is 1001', | |
'Zemian is a good programmer.', | |
'Zemian\'s id is 1001.' | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment