⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 retest.java

📁 jakarta-regexp-1.5 正则表达式的源代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        result = r.match("b");        say("b = " + result);        showParens(r);        if (!result) {            fail("\"b\" doesn't match to precompiled \"a*b\"");        }        result = r.match("c");        say("c = " + result);        showParens(r);        if (result) {            fail("\"c\" matches to precompiled \"a*b\"");        }        result = r.match("ccccaaaaab");        say("ccccaaaaab = " + result);        showParens(r);        if (!result) {            fail("\"ccccaaaaab\" doesn't match to precompiled \"a*b\"");        }    }    private void testSplitAndGrep()    {        String[] expected = {"xxxx", "xxxx", "yyyy", "zzz"};        RE r = new RE("a*b");        String[] s = r.split("xxxxaabxxxxbyyyyaaabzzz");        for (int i = 0; i < expected.length && i < s.length; i++) {            assertEquals("Wrong splitted part", expected[i], s[i]);        }        assertEquals("Wrong number of splitted parts", expected.length,                     s.length);        r = new RE("x+");        expected = new String[] {"xxxx", "xxxx"};        s = r.grep(s);        for (int i = 0; i < s.length; i++)        {            say("s[" + i + "] = " + s[i]);            assertEquals("Grep fails", expected[i], s[i]);        }        assertEquals("Wrong number of string found by grep", expected.length,                     s.length);    }    private void testSubst()    {        RE r = new RE("a*b");        String expected = "-foo-garply-wacky-";        String actual = r.subst("aaaabfooaaabgarplyaaabwackyb", "-");        assertEquals("Wrong result of substitution in \"a*b\"", expected, actual);        // Test subst() with backreferences        r = new RE("http://[\\.\\w\\-\\?/~_@&=%]+");        actual = r.subst("visit us: http://www.apache.org!",                         "1234<a href=\"$0\">$0</a>", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "visit us: 1234<a href=\"http://www.apache.org\">http://www.apache.org</a>!", actual);        // Test subst() with backreferences without leading characters        // before first backreference        r = new RE("(.*?)=(.*)");        actual = r.subst("variable=value",                         "$1_test_$212", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "variable_test_value12", actual);        // Test subst() with NO backreferences        r = new RE("^a$");        actual = r.subst("a",                         "b", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "b", actual);        // Test subst() with NO backreferences        r = new RE("^a$", RE.MATCH_MULTILINE);        actual = r.subst("\r\na\r\n",                         "b", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "\r\nb\r\n", actual);        // Test for Bug #36106        r = new RE("fo(o)");        actual = r.subst("foo",                         "$1", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "o", actual);        // Test for Bug #36405        r = new RE("^(.*?)(x)?$");        actual = r.subst("abc",                         "$1-$2", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "abc-", actual);        r = new RE("^(.*?)(x)?$");        actual = r.subst("abcx",                         "$1-$2", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "abc-x", actual);        r = new RE("([a-b]+?)([c-d]+)");        actual = r.subst("zzabcdzz",                         "$1-$2", RE.REPLACE_BACKREFERENCES);        assertEquals("Wrong subst() result", "zzab-cdzz", actual);    }    public void assertEquals(String message, String expected, String actual)    {        if (expected != null && !expected.equals(actual)            || actual != null && !actual.equals(expected))        {            fail(message + " (expected \"" + expected                 + "\", actual \"" + actual + "\")");        }    }    public void assertEquals(String message, int expected, int actual)    {        if (expected != actual) {            fail(message + " (expected \"" + expected                 + "\", actual \"" + actual + "\")");        }    }    /**     * Converts yesno string to boolean.     * @param yesno string representation of expected result     * @return true if yesno is "YES", false if yesno is "NO"     *         stops program otherwise.     */    private boolean getExpectedResult(String yesno)    {        if ("NO".equals(yesno))        {            return false;        }        else if ("YES".equals(yesno))        {            return true;        }        else        {            // Bad test script            die("Test script error!");            return false; //to please javac        }    }    /**     * Finds next test description in a given script.     * @param br <code>BufferedReader</code> for a script file     * @return strign tag for next test description     * @exception IOException if some io problems occured     */    private String findNextTest(BufferedReader br) throws IOException    {        String number = "";        while (br.ready())        {            number = br.readLine();            if (number == null)            {                break;            }            number = number.trim();            if (number.startsWith("##"))            {                continue;            }            if (number.startsWith("#"))            {                break;            }            if (!number.equals(""))            {                say("Script error.  Line = " + number);                System.exit(-1);            }        }        return number;    }    /**     * Creates testcase for the next test description in the script file.     * @param br <code>BufferedReader</code> for script file.     * @return a new tescase or null.     * @exception IOException if some io problems occured     */    private RETestCase getNextTestCase(BufferedReader br) throws IOException    {        // Find next re test case        final String tag = findNextTest(br);        // Are we done?        if (!br.ready())        {            return null;        }        // Get expression        final String expr = br.readLine();        // Get test information        final String matchAgainst = br.readLine();        final boolean badPattern = "ERR".equals(matchAgainst);        boolean shouldMatch = false;        int expectedParenCount;        String[] expectedParens = null;        if (!badPattern) {            shouldMatch = getExpectedResult(br.readLine().trim());            if (shouldMatch) {                expectedParenCount = Integer.parseInt(br.readLine().trim());                expectedParens = new String[expectedParenCount];                for (int i = 0; i < expectedParenCount; i++) {                    expectedParens[i] = br.readLine();                }            }        }        return new RETestCase(this, tag, expr, matchAgainst, badPattern,                              shouldMatch, expectedParens);    }}final class RETestCase{    final private StringBuffer log = new StringBuffer();    final private int number;    final private String tag; // number from script file    final private String pattern;    final private String toMatch;    final private boolean badPattern;    final private boolean shouldMatch;    final private String[] parens;    final private RETest test;    private RE regexp;    public RETestCase(RETest test, String tag, String pattern,                      String toMatch, boolean badPattern,                      boolean shouldMatch, String[] parens)    {        this.number = ++test.testCount;        this.test = test;        this.tag = tag;        this.pattern = pattern;        this.toMatch = toMatch;        this.badPattern = badPattern;        this.shouldMatch = shouldMatch;        if (parens != null) {            this.parens = new String[parens.length];            System.arraycopy(parens, 0, this.parens, 0, parens.length);        } else {            this.parens = null;        }    }    public void runTest()    {        test.say(tag + "(" + number + "): " + pattern);        if (testCreation()) {            testMatch();        }    }    boolean testCreation()    {        try        {            // Compile it            regexp = new RE();            regexp.setProgram(test.compiler.compile(pattern));            // Expression didn't cause an expected error            if (badPattern)            {                test.fail(log, "Was expected to be an error, but wasn't.");                return false;            }            return true;        }        // Some expressions *should* cause exceptions to be thrown        catch (Exception e)        {            // If it was supposed to be an error, report success and continue            if (badPattern)            {                log.append("   Match: ERR\n");                success("Produces an error (" + e.toString() + "), as expected.");                return false;            }            // Wasn't supposed to be an error            String message = (e.getMessage() == null) ? e.toString() : e.getMessage();            test.fail(log, "Produces an unexpected exception \"" + message + "\"");            e.printStackTrace();        }        catch (Error e)        {            // Internal error happened            test.fail(log, "Compiler threw fatal error \"" + e.getMessage() + "\"");            e.printStackTrace();        }        return false;    }    private void testMatch()    {        log.append("   Match against: '").append(toMatch).append("'\n");        // Try regular matching        try        {            // Match against the string            boolean result = regexp.match(toMatch);            log.append("   Matched: ").append(result ? "YES" : "NO").append("\n");            // Check result, parens, and iterators            if (checkResult(result) && (!shouldMatch || checkParens()))            {                // test match(CharacterIterator, int)                // for every CharacterIterator implementation.                log.append("   Match using StringCharacterIterator\n");                if (!tryMatchUsingCI(new StringCharacterIterator(toMatch)))                    return;                log.append("   Match using CharacterArrayCharacterIterator\n");                if (!tryMatchUsingCI(new CharacterArrayCharacterIterator(toMatch.toCharArray(), 0, toMatch.length())))                    return;                log.append("   Match using StreamCharacterIterator\n");                if (!tryMatchUsingCI(new StreamCharacterIterator(new ByteArrayInputStream(toMatch.getBytes()))))                    return;                log.append("   Match using ReaderCharacterIterator\n");                if (!tryMatchUsingCI(new ReaderCharacterIterator(new StringReader(toMatch))))                    return;            }        }        // Matcher blew it        catch(Exception e)        {            test.fail(log, "Matcher threw exception: " + e.toString());            e.printStackTrace();        }        // Internal error        catch(Error e)        {            test.fail(log, "Matcher threw fatal error \"" + e.getMessage() + "\"");            e.printStackTrace();        }    }    private boolean checkResult(boolean result)    {        // Write status        if (result == shouldMatch) {            success((shouldMatch ? "Matched" : "Did not match")                    + " \"" + toMatch + "\", as expected:");            return true;        } else {            if (shouldMatch) {                test.fail(log, "Did not match \"" + toMatch + "\", when expected to.");            } else {                test.fail(log, "Matched \"" + toMatch + "\", when not expected to.");            }            return false;        }    }    private boolean checkParens()    {        // Show subexpression registers        if (RETest.showSuccesses)        {            test.showParens(regexp);        }        log.append("   Paren count: ").append(regexp.getParenCount()).append("\n");        if (!assertEquals(log, "Wrong number of parens", parens.length, regexp.getParenCount()))        {            return false;        }        // Check registers against expected contents        for (int p = 0; p < regexp.getParenCount(); p++)        {            log.append("   Paren ").append(p).append(": ").append(regexp.getParen(p)).append("\n");            // Compare expected result with actual            if ("null".equals(parens[p]) && regexp.getParen(p) == null)            {                // Consider "null" in test file equal to null                continue;            }            if (!assertEquals(log, "Wrong register " + p, parens[p], regexp.getParen(p)))            {                return false;            }        }        return true;    }    boolean tryMatchUsingCI(CharacterIterator matchAgainst)    {        try {            boolean result = regexp.match(matchAgainst, 0);            log.append("   Match: ").append(result ? "YES" : "NO").append("\n");            return checkResult(result) && (!shouldMatch || checkParens());        }        // Matcher blew it        catch(Exception e)        {            test.fail(log, "Matcher threw exception: " + e.toString());            e.printStackTrace();        }        // Internal error        catch(Error e)        {            test.fail(log, "Matcher threw fatal error \"" + e.getMessage() + "\"");            e.printStackTrace();        }        return false;    }    public boolean assertEquals(StringBuffer log, String message, String expected, String actual)    {        if (expected != null && !expected.equals(actual)            || actual != null && !actual.equals(expected))        {            test.fail(log, message + " (expected \"" + expected                      + "\", actual \"" + actual + "\")");            return false;        }        return true;    }    public boolean assertEquals(StringBuffer log, String message, int expected, int actual)    {        if (expected != actual) {            test.fail(log, message + " (expected \"" + expected                      + "\", actual \"" + actual + "\")");            return false;        }        return true;    }    /**     * Show a success     * @param s Success story     */    void success(String s)    {        if (RETest.showSuccesses)        {            test.say("" + RETest.NEW_LINE + "-----------------------" + RETest.NEW_LINE + "");            test.say("Expression #" + (number) + " \"" + pattern + "\" ");            test.say("Success: " + s);        }    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -