gpt4 book ai didi

Java 正则表达式注释和 HTTP 正文 POST 的要求

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

我刚刚完成了一个从 POST 方法返回字符串的项目。返回的字符串是“答案”,POST BODY 接受字符串“问题”。我的对象属性如下:

@NotNull(message = "Question can't be null.")
@NotEmpty(message = "Question must contain text.")
@Pattern(regexp = "\\?$",
message = "Invalid question. Requires a question mark at the end.")
private String question;
private String answer;

POSTMapping如下:

@PostMapping(value = "/answer")
@ResponseStatus(HttpStatus.OK)
public String getOneAnswer(@RequestBody @Valid String question) throws Exception {

if(question.equals("")) {
String missingInputErrorMessage = "question input is an empty or does not exist.";
throw new IllegalArgumentException(missingInputErrorMessage);
}

int random = random.nextInt((10) + 1);
for(Answers answer: seriesOfAnswers) {
if(random == answer.getAnswerId()) {
return answer.getAnswer().toString();
}
}

return "Return this string if all else fails";
}

我所做的帖子正文如下:

{
"question": "This is a question"
}

{
"question": "This is a question?"
}

目前正则表达式不验证 POST BODY 末尾是否有 ?。不管怎样,它只是运行答案。如果我将输入更改为对象类型,则正则表达式会验证并显示消息,无论是否存在 ? 。我的问题是这样的:如果可以使用这种格式的正则表达式,我如何让正则表达式正确验证帖子正文中的“问题”值以 ? 结尾?

编辑:下面,艾玛提到我的实现可能不正确。她是对的。目前,可能有更好的方法来处理这个问题,但在听取她的建议时,我决定不使用 @Pattern 注释,而是在 @PostMapping 部分中进行正则表达式调用。

@PostMapping(value = "/answer")
@ResponseStatus(HttpStatus.OK)
public String getOneAnswer(@RequestBody @Valid String question) throws Exception {

// The string with the regex we'll need to use. "q" for question.
String qMarkEndingRegex = "\\?$";
// The pattern we're going to check.
Pattern checkForQMark = Pattern.compile(qMarkEndingregex, Pattern.MULTILINE);
// The matcher to actually check the question
Matcher qMarkMatcher = checkForQMark.matcher(question);

// if the matcher does NOT detect a question mark as the regex states, run this code.
if (!qMarkMatcher.find()) {
String needsQ = "You need to add a question mark at the end of your question.";
return needsQ;
}

最佳答案

你的表达很好,应该可以正常工作,也许你没有正确实现它:

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


public class RegularExpression{

public static void main(String[] args){

final String regex = "\\?\\s*$";
final String string = "This is a question?\n"
+ "This is a question? ";

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

while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}

Demo

<小时/>

如果您想简化/修改/探索表达式,regex101.com 的右上角面板已对此进行了解释。 。如果您愿意,也可以在 this link 观看,它如何与一些示例输入相匹配。

<小时/>

关于Java 正则表达式注释和 HTTP 正文 POST 的要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58360071/

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