gpt4 book ai didi

java - 使用 Java 验证正则表达式

转载 作者:行者123 更新时间:2023-12-01 19:13:33 25 4
gpt4 key购买 nike

我需要使用正则表达式验证字符串,该字符串必须类似于“createRobot(x,y)”,其中 x 和 y 是数字。

我有类似的东西

    String ins; 

Pattern ptncreate= Pattern.compile("^createRobot(+\\d,\\d)");
Matcher m = ptncreate.matcher(ins);
System.out.println(m.find());

但是不起作用

你能帮我吗?

谢谢。

最佳答案

您忘记了模式中的“机器人”一词。另外,括号是正则表达式中的特殊字符,+ 应放在 \d 之后,而不是 (:

Pattern.compile("^createRobot\\(\\d+,\\d+\\)$")

请注意,如果您想验证仅包含此“createRobot”字符串的输入,您也介意这样做:

boolean success = s.matches("createRobot\\(\\d+,\\d+\\)");

其中 s 是您要验证的String。但如果您想检索匹配的数字,您确实需要使用模式/匹配器:

Pattern p = Pattern.compile("createRobot\\((\\d+),(\\d+)\\)");
Matcher m = p.matcher("createRobot(12,345)");
if(m.matches()) {
System.out.printf("x=%s, y=%s", m.group(1), m.group(2));
}

如您所见,调用 Matcher.matches() (或 Matcher.find())后,您可以检索第 n通过group(n)进行匹配组。

关于java - 使用 Java 验证正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7628010/

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