我有一个格式为{Key=value, Key=value.....}
的字符串,我必须为它编写一个验证器。以上键值之间用空格{Key=value, Key=value, Key=value.....}
分隔。我对正则表达式完全陌生,但参考我写的堆栈溢出中的一个答案:
Boolean check = Pattern.matches("(\{+)?(\w+)?=(\w+)?,?","string to be validated");
但是这个方法行不通。
期望的字符串也可能是empty()
或<null>
的确切类型?
任何帮助都是感激的。
您可以在s*,s*
上分割字符串,然后检查结果数组中的每个元素是否与w+s*=s*w+
匹配。
public class Main {
public static void main(String[] args) {
// Test strings
String[] arr = { "{Key1=value1, Key2=value2}", "{Key=Value,Key=key=value}" };
boolean valid = true;
for (String s : arr) {
System.out.println(s + " => " + (!isValid(s) ? "false" : "true"));
}
}
static boolean isValid(String str) {
boolean valid = true;
String regex = "\w+\s*=\s*\w+";
String[] entries = str.replaceAll("[\{\}]", "").split("\s*,\s*");
for (String entry : entries) {
if (!entry.matches(regex)) {
valid = false;
break;
}
}
return valid;
}
}
输出:
{Key1=value1, Key2=value2} => true
{Key=Value,Key=key=value} => false
注意:
s*,s*
指定0个或多个空格字符,逗号后跟0个或多个空格字符。w+s*
指定一个或多个单词字符后跟零个或多个空白字符。