gpt4 book ai didi

java - 如何匹配字符串中的模式,其中要匹配的字符串为 "operands": ["10000"]

转载 作者:行者123 更新时间:2023-11-30 05:29:34 27 4
gpt4 key购买 nike

我有一个很长的 json 字符串,"attributeName":"Loc ID"},"operands":["10000"]}],"Frequency":{"type":" 这个只是其中的一部分,我只想在给定字符串中匹配此模式 "operands":["10000"]

我已经尝试过使用

string.replace("\"操作数\":[\"10000\"]","\"操作数\":[\"20000\"]")

甚至尝试过正则表达式 "\"operands\":[\"\\d+\"]"

我正在使用JAVA来获得想要的结果。

最佳答案

也许,这个表达,

"operands"\\s*:\\s*\\[\\s*"(\\d*)"\\s*\\]

以及替换,

"operands":["20000"]

可能工作得很好。

<小时/>

如果没有额外的空间,

\"operands\":\\[\"(\\d*)\"\\]

可能工作得很好。

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{

public static void main(String[] args){

final String regex = "\"operands\"\\s*:\\s*\\[\\s*\"\\s*(\\d*)\\s*\"\\s*\\]";
final String string = "\"attributeName\":\"Loc ID\"},\"operands\":[\"10000\"]}],\"frequency\":{\"type\":\"\n"
+ "\"attributeName\":\"Loc ID\"},\"operands\":[ \" 10000 \" ]}],\"frequency\":{\"type\":\"";
final String subst = "\"operands\":[\"20000\"]";

final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(string);

final String result = matcher.replaceAll(subst);

System.out.println(result);

}
}

输出

"attributeName":"Loc ID"},"operands":["20000"]}],"frequency":{"type":"
"attributeName":"Loc ID"},"operands":["20000"]}],"frequency":{"type":"
<小时/>

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

<小时/>

关于java - 如何匹配字符串中的模式,其中要匹配的字符串为 "operands": ["10000"],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57847889/

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