【问题标题】:(DEFINE) feature in regex does not work in Java正则表达式中的 (DEFINE) 功能在 Java 中不起作用
【发布时间】:2019-09-19 23:15:33
【问题描述】:

我正在尝试使用正则表达式验证 JSON 字符串。从另一篇帖子https://stackoverflow.com/a/3845829/7493427 中找到有效的正则表达式 它使用正则表达式中的 DEFINE 功能。但我认为 JRegex 库不支持该功能。有解决办法吗?

我首先使用了 java.util.regex,然后发现了 JRegex 库。但这也行不通。

String regex = "(?(DEFINE)" +
"(?<number>   -? (?= [1-9]|0(?!\\d) ) \\d+ (\\.\\d+)? ([eE] [+-]? 
\\d+)? )" +
"(?<boolean>   true | false | null )" +
"(?<string>    \" ([^\"\\n\\r\\t\\\\\\\\]* | \\\\\\\\ 
[\"\\\\\\\\bfnrt\\/] | \\\\\\\\ u [0-9a-f]{4} )* \" )" +
"(?<array>     \\[  (?:  (?&json)  (?: , (?&json)  )*  )?  \\s* 
\\] )" +
"(?<pair>      \\s* (?&string) \\s* : (?&json)  )" +
"(?<object>    \\{  (?:  (?&pair)  (?: , (?&pair)  )*  )?  \\s* 
\\} )" +
"(?<json>   \\s* (?: (?&number) | (?&boolean) | (?&string) | (? 
&array) | (?&object) ) \\s* )" +
")" +
"\\A (?&json) \\Z";
String test = "{\"asd\" : \"asdasdasdasdasdasd\"}";
jregex.Pattern pattern = new jregex.Pattern(regex);
jregex.Matcher matcher = pattern.matcher(test);
if(matcher.find()) {
    System.out.println(matcher.groups());
}

我希望匹配,因为测试 json 是有效的,但我得到了一个异常。

线程“主”jregex.PatternSyntaxException 中的异常:条件表达式中的未知组名:在 jregex.Term.makeTree(Term.java:219) 在 jregex.Term.makeTree(Term.java:360) 在 jregex 定义.Term.makeTree(Term.java:206) 在 jregex.Pattern.compile(Pattern.java:164) 在 jregex.Pattern.(Pattern.java:150) 在 jregex.Pattern.(Pattern.java:108) 在 com .cloak.utilities.regex.VariableValidationHelper.main(VariableValidationHelper.java:305)

【问题讨论】:

  • 使用正则表达式来“解析”JSON 是一个非常非常非常糟糕的主意。你最好使用专用的解析器。
  • 我正在使用 REGEX 验证 JSON 字符串,而不是尝试解析它。请正确阅读问题。
  • 解析包括验证,因此使用像 Jackson 这样的解析器可能会毫无问题地工作
  • 来自链接的帖子:大多数现代正则表达式实现都允许递归正则表达式 [..] -> java doesn't allow recursive regex

标签: java regex


【解决方案1】:

您可以使用这个相当简单的 Jackson 设置:

private static final ObjectMapper MAPPER = new ObjectMapper();

public static boolean isValidJson(String json) {
    try { 
        MAPPER.readValue(json, Map.class);
        return true;
    } catch(IOException e) {
        return false;
    }
}

当输入无效时ObjectMapper#readValue()会抛出JsonProcessingExceptions(IOException的子类)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 2020-07-08
相关资源
最近更新 更多