java - 正则表达式根据允许的分隔符的第一次出现来分割过滤字符串并获取键、运算符、值

标签 java regex regex-greedy

目前,我正在开发一个遗留代码库来支持我的一个 REST API 的过滤器。目前我们支持 3 个运算符,分别是 : Equal、! Not Equal、~ Like。当前代码拆分通过过滤器 String 并创建一个 String 数组,基于最终包含 key,op,value 的正则表达式。如果字符串数组大小不等于3,则会抛出异常。

//String filter1="name:ALTAF"; // Splitting correctly of size 3
//String filter2="name~:PDF"; // Not Splitting correctly - Goes in catch block.
String filter3="effectiveStartDateTime:2019-07-25T07:00"; // Not Splitting correctly - Goes in catch block.
String[] filterArray = filter3.split("((?<=[!:~><])|(?=[!:~><]))");

if (filterArray.length == 3) {
     String key = filterArray[0].trim();
     String op = filterArray[1].trim();
     String value = filterArray[2].trim();
     System.out.println("filter key =>" + key);
     System.out.println("filter operator =>" +op);
     System.out.println("filter value =>"+ value);
     }
     else {
         //throw Exception for invalid filter criteria.
     }

对于我的过滤器场景,我传递的过滤器字符串是 effectiveStartDateTime:2019-07-25T07:00 ,当前正则表达式在遇到 :< 时将其分割并给出大于 3 的大小 两次。

我已更改正则表达式以包含限制。

String[] filterArray = filter3.split("((?<=[!:~><])|(?=[!:~><]))",3);

正确分割过滤字符串 => Key- effectiveStartDateTime , Operator- : , Value- 2019-07-24T07:00

所以我在上面尝试做的是根据允许的运算符的第一次出现来分割正则表达式(: ! ~)存在于过滤字符串中,如果获取的字符串数组大小超过 3,照常抛出异常。

但在一种负面情况下它会失败,我将过滤器字符串传递为 - name~:PDF ,如下所示 键 - name ,运算符 - ~ ,值 - :PDF

其中给出的大小不是 4,而是给出了 3 并且通过了。但我想要的是,根据允许的运算符(:!〜)分割过滤器字符串,在这种情况下,我应该得到大小为4。

有人可以指导我吗?

干杯 山姆

最佳答案

我认为您无法通过拆分来实现这一目标。 但是,如果您仍然想使用正则表达式,您可以使用 Matchers。

在下面的示例中,我定义了一个可以多次使用的静态模式。 我将匹配完整的输入字符串。 允许多次使用第一个运算符。 然而,如果出现其他运算符,则组 other 将是匹配器,因此不为空。 其他字符串可以通过命名捕获组访问。

static Pattern pattern = Pattern.compile("^(?<key>.*?)(?<op>[:~!])(?<value>(?:[^:~!]|\\k<op>)*+)(?<other>.+)?$");
public static void interpret(String filter){
    Matcher matcher = pattern.matcher(filter);
    if(!matcher.matches()){
        throw new RuntimeException("invalid input");
    }
    if(matcher.group("other") != null){
        throw new RuntimeException("multiple operators");
    }
    String key = matcher.group("key").trim();
    String op = matcher.group("op").trim();
    String value = matcher.group("value").trim();
    System.out.printf("key=\"%s\", op=\"%s\", value=\"%s\"\n", key, op, value);
}

关于java - 正则表达式根据允许的分隔符的第一次出现来分割过滤字符串并获取键、运算符、值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57374622/

相关文章:

Javascript 贪婪的正则表达式似乎是非贪婪的

java - 打印 10x10 表中列表的元素

java - 在 000webhost 服务器上上传时,每个循环都不会执行

Java 编程语言语法

java - 模糊和聚焦紧密耦合?

javascript - 名称的正则表达式,文本之间允许有空格,没有文本时避免空格

正则表达式双列匹配 R

Java 正则表达式 - 添加括号使其变得贪婪?

Javascript 替换功能不会删除引号

python - 正则表达式未在 python 中返回预期的输出