Upgrade Regex with a tester() method?
Peter Levart
peter.levart at gmail.com
Mon Jan 21 09:20:26 PST 2013
On 01/21/2013 10:25 AM, Paul Sandoz wrote:
> On Jan 20, 2013, at 7:04 PM, Peter Levart <peter.levart at gmail.com> wrote:
>
>> On 01/04/2013 04:07 PM, Brian Goetz wrote:
>>> Seems a nice "point lambdafication" suggestion. (The naming convention
>>> we've been using as "asPredicate()".)
>>>
>>>
>>> Regex is one of those areas where we wanted to do more with
>>> lambdafication, but just didn't have the time to work through it. If
>>> you want to suggest more...
>> If that is being considered, I would suggest to include all 3 variants
>> of matching (corresponding to 3 methods of Matcher):
>>
>> public Predicate<String> asFindPredicate()
>> public Predicate<String> asLookingAtPredicate()
>> public Predicate<String> asMatchesPredicate()
>>
>> Without "as" might even sound better since there are three of them:
>>
>> public Predicate<String> findPredicate()
>> public Predicate<String> lookingAtPredicate()
>> public Predicate<String> matchesPredicate()
>>
>>
> I question whether such methods carry enough weight, given that it is really easy to state:
>
> () -> p.find()
>
> or
>
> Pattern::find
Well, it's a little longer:
(s) -> p.matcher(s).find()
But I agree, those are to simple expressions to carry a weight for
introduction of a new method...
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
);
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);
Regards, Peter
>
> My preference is to encourage usage of such expressions rather than pick some boolean returning zero parameter methods of some classes to be "overloaded" with Predicate-based alternatives.
>
> Paul.
>
More information about the lambda-dev
mailing list