20

I have tests where I validate the output with a regex. When it fails it reports that output X did not match regex Y.

I would like to add some indication of where in the string the match failed. E.g. what is the farthest the matcher got in the string before backtracking. Matcher.hitEnd() is one case of what I'm looking for, but I want something more general.

Is this possible to do?

Nickolay
  • 31,095
  • 13
  • 107
  • 185
TimK
  • 4,635
  • 2
  • 27
  • 27
  • 1
    This is probably your best bet: http://stackoverflow.com/questions/2348694/how-do-you-debug-a-regex – Reverend Gonzo May 04 '11 at 19:55
  • @Reverend Gonzo: Thanks, Perl's "use re 'debug'" is close to what I'm looking for. Something similar that is callable from Java would be great. – TimK May 07 '11 at 00:24

4 Answers4

9

If a match fails, then Match.hitEnd() tells you whether a longer string could have matched. In addition, you can specify a region in the input sequence that will be searched to find a match. So if you have a string that cannot be matched, you can test its prefixes to see where the match fails:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LastMatch {
    private static int indexOfLastMatch(Pattern pattern, String input) {
        Matcher matcher = pattern.matcher(input);
        for (int i = input.length(); i > 0; --i) {
            Matcher region = matcher.region(0, i);
            if (region.matches() || region.hitEnd()) {
                return i;
            }
        }

        return 0;
    }

    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("[A-Z]+[0-9]+[a-z]+");
        String[] samples = {
                "*ABC",
                "A1b*",
                "AB12uv",
                "AB12uv*",
                "ABCDabc",
                "ABC123X"
        };

        for (String sample : samples) {
            int lastMatch = indexOfLastMatch(pattern, sample);
            System.out.println(sample + ": last match at " + lastMatch);
        }
    }
}

The output of this class is:

*ABC: last match at 0
A1b*: last match at 3
AB12uv: last match at 6
AB12uv*: last match at 6
ABCDabc: last match at 4
ABC123X: last match at 6
Andreas Mayer
  • 687
  • 5
  • 15
  • This is good, though I find the second case confusing. The entire string matches, so why report 4? I suggest: `region.matches(); if (region.hitEnd()) ...`. Then it returns 6 for that case. – TimK May 20 '14 at 21:34
  • Good catch. I only tested for partial matches and didn't take into account full matches of the complete string or any of its prefixes. This is now fixed. – Andreas Mayer May 21 '14 at 09:49
3

You can take the string, and iterate over it, removing one more char from its end at every iteration, and then check for hitEnd():

int farthestPoint(Pattern pattern, String input) {
    for (int i = input.length() - 1; i > 0; i--) {
        Matcher matcher = pattern.matcher(input.substring(0, i));
        if (!matcher.matches() && matcher.hitEnd()) {
            return i;
        }
    }
    return 0;
}
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
1

You could use a pair of replaceAll() calls to indicate the positive and negative matches of the input string. Let's say, for example, you want to validate a hex string; the following will indicate the valid and invalid characters of the input string.

String regex = "[0-9A-F]"
String input = "J900ZZAAFZ99X"
Pattern p = Pattern.compile(regex)
Matcher m = p.matcher(input)
String mask = m.replaceAll('+').replaceAll('[^+]', '-')
System.out.println(input)
System.out.println(mask)

This would print the following, with a + under valid characters and a - under invalid characters.

J900ZZAAFZ99X
-+++--+++-++-
Go Dan
  • 15,194
  • 6
  • 41
  • 65
0

If you want to do it outside of the code, I use rubular to test the regex expressions before sticking them in the code.

lobster1234
  • 7,679
  • 26
  • 30
  • 1
    Unless I'm missing something, this tells me if text doesn't match a regex, but it doesn't tell me where it fails to match. That's what I'm looking for. – TimK Apr 14 '11 at 21:58