All the Perl that's Practical to Extract and Report

Navigation

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
Without JavaScript enabled, you might want to
use the classic discussion system instead. If you login, you can remember this preference.

Please Log In to Continue

First of all there is a convenience method of matches for a Pattern.boolean b = Pattern.matches("a*b", "aaaaaab");

That suffices for the common case. (Too bad they didn't think of allowing matches to pass in flags to compile with.)

Java allows you to reuse the same pattern over and over again. It is more verbose than it would be if they had a utility function of matches on a Pattern, but the functionality is there. Plus there is always the possibility that Java will be smart enough at some point to automatically optimize the naive code for you either at the compilation or the JIT level. (I don't know if that is built yet. But it seems doable. And that is in my eyes a better solution than extending the API more.)

Anyways the real point of the Matcher object is to allow people to loop over a match. In Perl you could write:while ($string =~/(\w+)/g) {
my $word = $1;...}

In Java you would do that with something like this:Pattern find_word = Pattern.compile("\\w+");Matcher m = find_word.matcher(string);while (m.find()) {// m.start and m.end tell me where the match is.}

That does seem to show a use case for the Matcher object. For the record, I almost never loop over a match in Perl. I just don't seem to find it necessary. I know why you'd want to, though, so Java should make that possible.

Interestingly enough, that seems to be the only explictly java.util.regex-related way to accomplish a s///g, as well, although there's a regex-related method in the String class that will do it.

--J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers