将模式匹配到Java中的输入

时间:2016-02-19 21:43:14

标签: java regex

所以我在编码挑战中遇到了这个问题而且很丢失。我需要编写一个接受模式并将其与输入匹配的函数。例如,模式为abba,输入为bluegreengreenblue。 在这种情况下,函数返回true,因为输入与模式匹配。 如果相同模式的输入为bluebluegreengreen,则答案将为假。 本质上我正在尝试编写一个函数,

boolean wordpattern(String pattern, string input){

     //process input to match pattern
     // return true if it matches
    //return false if it doesn't
}

输入不一定是有意义的单词。它可以是axcdefdeefdeaxcd 有人可以帮助我使用算法开始解决问题。我想不出有任何方法可以开始解决这个问题。

2 个答案:

答案 0 :(得分:1)

您可以将此惰性匹配正则表达式与反向引用一起使用:

(.+?)(.+?)\2\1

RegEx Demo

它将匹配任何foobarbarfoo

RegEx分手:

(.+?)   # match 1 or more any char and group it as capture group #1 (lazy)
(.+?)   # match 1 or more any char and group it as capture group #2 (lazy)
\2      # back-reference to capture group #2
\1      # back-reference to capture group #1

答案 1 :(得分:1)

我建议生成一个正则表达式。然后将此生成的正则表达式应用于您的文本。

生成正则表达式时,对每个第一次出现的字符使用(.+),然后使用\1\2等引用它。

代码可能如下所示:

import java.util.*;
import java.util.regex.Pattern;

public class X {

    public static void main(String[] args) {
        wordpattern("abba", "bluegreengreenblue");
    }

    protected static boolean wordpattern(String pattern, String input) {
        Map<Character,Integer> patternItemNumbers = new HashMap<>();
        StringBuilder regularExpression = new StringBuilder();
        int groupCount = 1;

        for (char patternItem : pattern.toCharArray()) {
            Integer group = patternItemNumbers.get(patternItem);

            // first occurrence: create new fetching group
            if (group == null) {
                regularExpression.append("(.+)");
                patternItemNumbers.put(patternItem, groupCount++);
            }

            // every next occurrence: reuse group by identifier
            else {
                regularExpression.append('\\');
                regularExpression.append(group);
            }
        }

        String regexp = regularExpression.toString();
        boolean matches = Pattern.matches(regexp, input);

        System.out.println("pattern: "+pattern);
        System.out.println("regular expression: "+regexp);
        System.out.println("matches: "+matches);

        return matches;
    }

}

输出:

pattern: abba
regular expression: (.+)(.+)\2\1
matches: true

另一个例子:wordpattern("aaab", "bluebluebluegreen");将输出:

pattern: aaab
regular expression: (.+)\1\1(.+)
matches: true