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

标签 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”的正则表达式,它从第二个字符串 longLine 返回 hello。不确定正则表达式是否是正确的解决方案,但我想知道它是否可行。

最佳答案

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

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

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();
}

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

关于Java,正则表达式可以带变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172281/

相关文章:

java - 使用 JFrame 获取最大屏幕尺寸

java - 如何使用 NetBeans 在 Java 程序中包含文本文件

java - 何时在 Spring 中使用 ElementFactory 方法

javascript - a.toString().replace(/^(\d)$/, "0$1")?

c - 如何在C中计算字符串的字符并将它们分配给不同的组(小写和大写)

java - 使用 Canvas.drawText 从位图上的 TextView 获取错误的 Y 坐标

php - preg 比赛计数比赛

regex - 如何排除一组单词但在qregexp中包含另一组单词?

java - 似乎是数字的字符串的 NumberFormatException

java - 如何在android中将单行数据存储到sqlite数据库的字符串数组中