Last active
May 9, 2017 16:40
-
-
Save n1chre/cc6efdeff95bdb6ac585d2c45df3a8ef to your computer and use it in GitHub Desktop.
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
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.function.Function; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
public class Replacer { | |
public static void main(String[] args) { | |
Replacer replacer = new Replacer(); | |
replacer.addReplacement(Replacer.NUMBER, numberString -> "(" + numberString + ")"); | |
System.out.println( | |
replacer.replace("ovo je neki broj 1.4213 a ovo je neki drugi -123e10") | |
); | |
} | |
/** | |
* Regular expression for finding numbers in double format | |
*/ | |
public static final String NUMBER = "[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?"; | |
private Map<Pattern, Function<String, String>> replacers = new HashMap<>(); | |
public void addReplacement(String regex, Function<String, String> replacer) { | |
replacers.put(Pattern.compile(regex), replacer); | |
} | |
public String replace(String s) { | |
StringBuffer buffer = new StringBuffer(); | |
for (Map.Entry<Pattern, Function<String, String>> e : replacers.entrySet()) { | |
buffer.setLength(0); // empty | |
Matcher m = e.getKey().matcher(s); | |
while (m.find()) { | |
m.appendReplacement(buffer, e.getValue().apply(m.group())); | |
} | |
m.appendTail(buffer); | |
s = buffer.toString(); | |
} | |
return s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment