HTTP正文POST的Java Regex注释和要求

问题描述 投票:1回答:1

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

@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;

POSMapping如下:

@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";
}

我完成的POSTS的身体如下:

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

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

当前正则表达式无法验证POST BODY末尾是否有?。无论如何,它只是运行答案。如果我将输入更改为对象类型,则无论是否存在?,正则表达式都会进行验证并向我显示该消息。我的问题是:如果可以这种格式使用正则表达式,我如何获取正则表达式以正确验证POST BODY中的“问题”值以?结尾?

编辑:下面,艾玛(Emma)提到我的实现可能不正确。她是对的。当前,可能有更好的方法来处理此问题,但是在听取她的建议时,我决定不使用@Pattern批注,而是在@PostMapping部分中进行regex调用。

@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;
    }
java regex validation post annotations
1个回答
1
投票

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

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中查看它如何与某些示例输入匹配。


© www.soinside.com 2019 - 2024. All rights reserved.