[key1:value1,key2:value2,key3:value3],[key21:value21,key22:value22]的正则表达式

时间:2017-05-26 07:15:17

标签: java regex

我想检查给定的String是否与以下格式匹配:

[key1:value1,key2:value2,key3:value3],[key21:value21,key22:value22]..

可能有1个或多个[。*]标记(用逗号分隔),在[]括号内,我们可以有一个或多个key:value对。 我用过:

(\\[(.*:.*)+(,*)\\]+),*

但不幸的是它通过了:

*[key1:value1][key2:value2] (comma is missing between [] tokens)
*[key1:value1][invalid] (second token was invalid format)

你能帮我改进上面的正则表达式吗?

1 个答案:

答案 0 :(得分:2)

您可以保留2个字符:冒号:和逗号,

因此,您可以将键和值定义为:[^:,]+(任何字符中的一个或多个,冒号和逗号除外)。

然后是一个键值对:[^:,]+:[^:,]+

以下是my test program

private static final String GOOD_1 = "[key1:value1,key2:value2,key3:value3],[key21:value21,key22:value22]";
private static final String GOOD_2 = "[key1:value1],[key21:value21]";
private static final String GOOD_3 = "[key1:value1]";
private static final String BAD_1 = "[key1:value1],[key21]";

private static final String KEY_VALUE = "[^:,]+:[^:,]+";
private static final String TOKEN = "\\[" + KEY_VALUE + "(," + KEY_VALUE + ")*\\]";
private static final String REGEX = TOKEN + "(," + TOKEN + ")*";

public static void main (String[] args)
{
    System.out.println("REGEX is " + REGEX);
    System.out.println(GOOD_1 + " is " + check(GOOD_1));
    System.out.println(GOOD_2 + " is " + check(GOOD_2));
    System.out.println(GOOD_3 + " is " + check(GOOD_3));
    System.out.println(BAD_1 + " is " + check(BAD_1));
}

private static boolean check(String str) {
     return str.matches(REGEX);
}

如果你运行它,你将获得输出:

REGEX is \[[^:,]+:[^:,]+(,[^:,]+:[^:,]+)*\](,\[[^:,]+:[^:,]+(,[^:,]+:[^:,]+)*\])*

[key1:value1,key2:value2,key3:value3],[key21:value21,key22:value22] is true
[key1:value1],[key21:value21] is true
[key1:value1] is true
[key1:value1],[key21] is false

但是,如果您的输入数据是JSON格式,那么您不应该通过尝试为其创建正则表达式来浪费您的时间。将其传递给a JSON parser