Java,可以正则表达式的变量吗?

时间:2017-02-11 04:35:24

标签: java regex string match

我将REGEX视为问题的可能解决方案。我制作了一些包含诸如hello,hellllooo,hhhheello等单词的示例字符串。然后,我创建了一个正则表达式来查找所有这些类型的单词。我不该做的是查看可能包含或不包含输入单词的句子。例如,你输入hellloo,我想扫描我的句子中类似于“hellloo”的单词,如果在句子中找到则返回'hello'。我可以创建一个类似于用户输入变量的正则表达式吗?如果你输入hellloo然后我会构造一些东西,从句子或文件中返回类似的单词到你的输入。

两个输入字符串

String line = "this is hello helloooo hellllooo hhhel hellll what can I do?";
String longLine = "hello man this what can up down where hey my there find now ok stuff jive super sam dude car";

我的正则表达式函数

public static void regexChecker(String theRegex, String str2Check) {
        Pattern checkRegex = Pattern.compile(theRegex);
        Matcher regexMatcher = checkRegex.matcher(str2Check);

        while(regexMatcher.find()) {
            if(regexMatcher.group().length() != 0) {
                System.out.println(regexMatcher.group().trim());
            }
        }
    }

运行此

regexChecker("\\s[h]*[e]*[l]*[l]*[o]*\\s", line);

返回

hello
hello
hellllooo
hellll

我想根据用户输入'helllooo'创建一个REGEX,它从第二个String longLine返回hello。不确定正则表达式是否是正确的解决方案,但我想知道它是否可行。

3 个答案:

答案 0 :(得分:1)

假设您的示例捕获了您想要执行的操作(输入字中重复的字母),您肯定可以。

从概念上讲,您需要以下内容:

public String makeRegec(String input) {
    StringBuilder regex = new StringBuilder("\\b");
    if(input != null && input.length() > 0) {

        for (int i = 0; i < input.length(); i++) {
            regex.append(input.charAt(i)).append("+");
        }
    }
    regex.append("\\b*");//don't need this if you would accept hello, for example
    return regex.toString();
}

当然,您可以编译模式并返回

答案 1 :(得分:1)

试试这个

制作正则表达式函数:

public static String makeRegex(String input) {
StringBuilder regex = new StringBuilder();
if(input != null && input.length() > 0) {

    for (int i = 0; i < input.length(); i++) {
        regex.append("[" + input.charAt(i) + "]{1,}");

    }
}
return regex.toString();
}

正则表达式功能:

public static ArrayList regexChecker(String theRegex, String str2Check) {
        Pattern checkRegex = Pattern.compile(theRegex);
        Matcher regexMatcher = checkRegex.matcher(str2Check);
       ArrayList<String> list = new ArrayList<>();
       String findString = "";
        while(regexMatcher.find()) {
            if(regexMatcher.group().length() != 0) {
                findString = regexMatcher.group().trim();
                list.add(findString);

            }
        }
        return list;
    }

使用:

String line = "this is hello helloooo hellllooo hhhel hellll what can I do?";

    String input = "hello";

    ArrayList<String> list = regexChecker(makeRegex(input), line);

    for(int i = 0;i<list.size();i++)
        System.out.println(list.get(i));

返回:

hello
helloooo
hellllooo

替换字符串:

System.out.println(line.replaceAll(makeRegex(input), input));

答案 2 :(得分:1)

试试这个:

String found = input.replaceAll(".*?((h)+(e)+(l)(l)+(o)+)?.*", "$2$3$4$5$6");

结果将是&#34;你好&#34;如果输入中没有像你好的话,则为空白。