Upgrade Regex with a tester() method?
Paul Sandoz
paul.sandoz at oracle.com
Tue Jan 22 00:29:08 PST 2013
On Jan 21, 2013, at 6:20 PM, Peter Levart <peter.levart at gmail.com> wrote:
>
> Another possible point lambdafication is an idiom that is frequent with using pattern matching - replacement:
>
> public class Pattern { ...
>
> public String replaceAll(String str, Function<String, String> replacementFunction) {
> Matcher m = matcher(str);
> StringBuffer sb = new StringBuffer();
> while (m.find()) {
> m.appendReplacement(sb, replacementFunction.apply(m.group(1)));
> }
> m.appendTail(sb);
> return sb.toString();
> }
>
> so one can write:
>
> Pattern pattern = Pattern.compile("\\{(.*?)\\}");
> String msg = pattern.replaceAll(
> "User's home is: {user.home}, current dir is: {user.dir}",
> System::getProperty
> );
>
Perhaps those function-based methods would be more appropriate on Matcher as overloads of replaceAll and replaceFirst?
Paul.
> This method could then also be overloaded on String as a shortcut without precompiled Pattern instance:
>
> public class String {...
>
> public String replaceAll(String regex, Function<String, String> replacementFunction) {
> return Pattern.compile(regex).replaceAll(this, replacementFunction);
> }
>
> so one could write:
>
> String msg = "User's home is: {user.home}, current dir is: {user.dir}"
> .replaceAll("\\{(.*?)\\}", System::getProperty);
>
More information about the lambda-dev
mailing list