2

我有一个具体的问题,我在网上找不到任何答案。基本上,我想对具有多种模式的文本运行模式匹配操作。但是,我不希望匹配器一次得到所有结果,而是在循环的不同阶段调用每个模式,同时在每个阶段执行特定操作。例如,假设我有Pattern1Pattern2Pattern3,我想要类似的东西:

 if (Pattern 1 = true) {
        delete Pattern1;
    } else if (Pattern 2 = true) {
        delete Pattern2;
    } else if (Pattern 3 = true) {
        replace with 'something;
    } .....and so on

(这只是循环的说明,所以可能语法不正确,)

我的问题是:如何编译不同的模式,同时分别调用它们?(我只看到多个模式一起编译并在 AND/OR 等的帮助下一起搜索......不幸的是,这不是我想要的)我可以将模式保存在一个数组中并在我的环形?

4

2 回答 2

2

准备您的Pattern对象pattern1, pattern2, pattern3并将它们存储在任何容器(数组或列表)中。然后在每次迭代时使用对象的usePattern(Pattern newPattern)方法循环这个容器。Matcher

于 2012-08-29T16:23:43.880 回答
1

您可以创建一个通用接口,并使用模式或任何其他您可能想要转换字符串的匿名实现:

interface StringProcessor {
    String process(String source);
}

StringProcessor[] processors = new StringProcessor[] {
    new StringProcessor() {
        private final Pattern p = Pattern.compile("[0-9]+");
        public String process(String source) {
            String res = source;
            if (p.matcher(source).find()) {
                res = ... // delete
            }
            return res;
        }
    }
,   new StringProcessor() {
        private final Pattern p = Pattern.compile("[a-z]+");
        public String process(String source) {
            String res = source;
            if (p.matcher(source).find()) {
                res = ... // replace
            }
            return res;
        }
    }
,   new StringProcessor() {
        private final Pattern p = Pattern.compile("[%^#@]{2,5}");
        public String process(String source) {
            String res = source;
            if (p.matcher(source).find()) {
                res = ... // do whatever else
            }
            return res;
        }
    }
};

String res = "My starting string 123 and more 456";
for (StringProcessor p : processors) {
    res = p.process(res);
}

请注意, 的实现StringProcessor.process根本不需要使用正则表达式。底部的循环不知道正则表达式参与获取结果。

于 2012-08-29T16:26:17.647 回答