How to use a regex group and backreference to verify file contents

  Kiến thức lập trình

I have a file with timestamps and want to verify the contents. Two lines within the file should have the same timestamp value (but the value changes from run to run). I want to verify that whatever value is present on the first of the two lines also appears on the second line.

I am trying to use a group, Matcher, and Pattern (first time for both) but am not getting consistent results. Sometimes false positive (the values differ but a match is reported), sometimes PatternSyntaxException:illegal/unsupported escape sequence. I have not yet gotten a true negative (values differ and not matched is reported)

My regEx file:

^TIMESTAMP CORRECTED TO ([0-9]{13})s*$
^INSTANCE WITH TIMESTAMP 1 REPLACEDs*$

I think the “1” is causing the PatternSyntaxException, so I escape it – “1” but that doesn’t report a mismatch.

This file should fail verification because the timestamps differ.

TIMESTAMP CORRECTED TO 2419211111111
INSTANCE WITH TIMESTAMP 24192100000000 REPLACED

The code gets as input each of the files’ contents as a List and then:

    boolean matched = true;

    String regEx = expectedLines.toString();

    String actualStr = actualLines.toString();

    Pattern pattern = Pattern.compile(regEx);
    Matcher matcher = pattern.matcher(actualStr);
    if (!matcher.matches()) {
        matched = false;
    }

Am I using the Pattern & Matcher classes correctly? Is reading from a file into a List<> then to a string acceptable? Is the regEx not correct?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT