有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在正则表达式中使用ArrayList中的字符串

我想知道如何检查字符串是否只包含ArrayList中的值,也可能包含ArrayList之外的值。比如:

ArrayList<String> array = new ArrayList<>();
array.add("min");
array.add("max");
array.add("abs");
String plus = "+";
Pattern pattern = Pattern.compile("?????"); // I'm asking what should I write here
Matcher matcher = pattern.matcher(line); // line is the String I want to check

呜呜呜呜。。。(line是我要检查的字符串)

我的意思是,我应该写什么来代替“什么?”例如,为了检查字符串行是否只包含数组中的精确字符串和字符串加号(“+”)

非常感谢


共 (3) 个答案

  1. # 1 楼答案

    阅读它,从中创建一个字符串

    StringBuilder builder = new StringBuilder();
    for(String str : array) {
      builder.append(str).append("|");
    }
    builder.setLength(builder.length() - 1);
    

    然后

    Pattern pattern = Pattern.compile("(" + builder.toString() + "|\\+)");
    

    我用了@Braj patten,我不知道是否正确

  2. # 2 楼答案

    check if the String line contains only the exact Strings from array and the string plus ("+")

    只需从数组中形成一个正则表达式。它将以这种形式^(min|max|abs)\+$

    这里^代表一行的开始,$代表精确匹配的行的结束

    在这里阅读更多模式Java Regex Pattern

  3. # 3 楼答案

    如果我没有错的话,你可以帮我寻找下面的代码

    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("min");
        array.add("max");
        array.add("abs");
        String line = "Max";
        Pattern pattern = null;
        boolean status = false;
        String plus = "+";
        for (String s : array) {
            pattern = Pattern.compile("\\b" + s + "\\b" + "[" + plus + "]",Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(line);
            if (matcher.find()) {
                status = true;
                break;
            }
        }
        if (status) {
            System.out.println("match");
        } else {
            System.out.println("not match");
        }
    }