gpt4 book ai didi

java - 具有 "{"的字符串的模式匹配

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:25 25 4
gpt4 key购买 nike

首先我做了这个-

String str = "{\"hits\":[{\"links_count\":6,\"forum_count\":11}],\"totalHitCount\":1}";

Assert.assertTrue(str.matches("{\"hits\":[{\"links_count\":[0-9]{1,},\"forum_count \":11}],\"totalHitCount\":[0-9]{1,}}"),
"Partnership message does not appear");

这让我出现以下错误 -

 Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
{"hits":[\{"links_count":[0-9]{1,},"forum_count":11}],"totalHitCount":[0-9]{1,}}

然后我做了(转义“{”)-

String str = "\\{\"hits\":[\\{\"links_count\":6,\"forum_count\":11\\}],\"totalHitCount\":1\\}";

Assert.assertTrue(str.matches("\\{\"hits\":[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}],\"totalHitCount\":[0-9]{1,}\\}"),
"Partnership message does not appear");

并得到以下错误-

Exception in thread "main" java.lang.AssertionError: Partnership message does not appear expected:<true> but was:<false>

我在这里错过了什么?

最佳答案

您不需要在输入中对 { [ 进行转义。但是您需要在正则表达式中转义 [ ]

试试这个:

String str = "{\"hits\":[{\"links_count\":6,\"forum_count\":11}],\"totalHitCount\":1}";

System.out.println(str.matches("\\{\"hits\":\\[\\{\"links_count\":[0-9]{1,},\"forum_count\":11\\}\\],\"totalHitCount\":[0-9]{1,}\\}"));

关于java - 具有 "{"的字符串的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6288242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com