Skip to content

Instantly share code, notes, and snippets.

@redsquirrel
Created October 14, 2008 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redsquirrel/16695 to your computer and use it in GitHub Desktop.
Save redsquirrel/16695 to your computer and use it in GitHub Desktop.
class SymbolReplacer {
protected String stringToReplace;
SymbolReplacer(String s) {
this.stringToReplace = s;
}
String replace() {
Pattern symbolPattern = Pattern.compile("\\$([a-zA-Z]\\w*)");
int startingPosition = 0;
while (true) {
Matcher symbolMatcher =
symbolPattern.matcher(stringToReplace.substring(startingPosition));
if (symbolMatcher.find()) {
startingPosition += replaceSymbol(symbolMatcher);
} else
break;
}
return stringToReplace;
}
private int replaceSymbol(Matcher symbolMatcher) {
String symbolName = symbolMatcher.group(1);
if (getSymbol(symbolName) != null)
stringToReplace = stringToReplace.replace("$" + symbolName,
translate(symbolName));
return symbolMatcher.start(1);
}
protected String translate(String symbolName) {
return getSymbol(symbolName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment