xyb1988825 2012-02-02 16:33
浏览 217
已采纳

java正则验证问题

以下正则验证返回不同的结果,请大家帮忙看下问题,使用的是org.apache.oro.text.regex这个包
[code="java"]PatternCompiler compiler = new Perl5Compiler();
PatternCompiler compiler2 = new Perl5Compiler();
try {

        Pattern p = compiler.compile(
                ".*\\s(and|or)\\s+.*([>=<]|\\slike\\s|\\sbetween\\s)+.*",
                Perl5Compiler.READ_ONLY_MASK);

        PatternMatcherInput input = new PatternMatcherInput(
                "30589 and 7659=7659");
        PatternMatcher matcher = new Perl5Matcher();

        System.out.println(matcher.contains(input, p)); //这个返回true

        System.out.println(matcher.contains(input, compiler2.compile(
                ".*\\s(and|or)\\s+.*([>=<]|\\slike\\s|\\sbetween\\s)+.*",
                Perl5Compiler.READ_ONLY_MASK))); //这个返回false
    } catch (MalformedPatternException e) {
        System.out.println("error");
    }[/code]
  • 写回答

1条回答 默认 最新

  • _1_1_7_ 2012-02-02 17:05
    关注

    API用的不对,参考:
    [quote]
    public boolean contains(PatternMatcherInput input,
    Pattern pattern)
    Determines if the contents of a PatternMatcherInput, starting from the current offset of the input contains a pattern. If a pattern match is found, a MatchResult instance representing the first such match is made acessible via getMatch(). The current offset of the PatternMatcherInput is set to the offset corresponding to the end of the match, so that a subsequent call to this method will continue searching where the last call left off. You should remember that the region between the begin and end offsets of the PatternMatcherInput are considered the input to be searched, and that the current offset of the PatternMatcherInput reflects where a search will start from. Matches extending beyond the end offset of the PatternMatcherInput will not be matched. In other words, a match must occur entirely between the begin and end offsets of the input. See PatternMatcherInput for more details.
    [/quote]


    PatternMatcherInput input = new PatternMatcherInput(

    "30589 and 7659=7659");

    换成String 类型就可以了
    String input="30589 and 7659=7659";

    PatternMatcherInput匹配一次后,offset就变了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于PLUS模型中kapaa值的问题
  • ¥15 关于博途V17进行仿真时无法建立连接问题
  • ¥15 请问下这个红框里面是什么文档或者记事本编辑器
  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥15 为什么安装HCL 和virtualbox之后没有找到VirtualBoxHost-OnlyNetWork?
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号