2011-10-02 141 views
0

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

我有类似

String ins; 

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

但不工作

你能帮助我吗?

谢谢。

+3

如果它应该是createRobot,你为什么在表达中只有“创造”? – stivlo

+0

我忘了发布它,但在代码中我有“createRobot”,对不起 – JuanS

回答

4

您忘记了您的模式中的单词Robot。此外,括号在正则表达式特殊字符,应该+后不(放在\d后:

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

请注意,如果您想验证输入应该只包括本"createRobot" -string,你心如做:

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())后,就可以检索ñ th match-group through group(n)

+0

非常感谢,真的有用,有什么方法可以获得数字“x”和“y”? – JuanS

+0

@JuanS,我在我的回答中加入了这个。别客气。 –

+0

这就是我正在寻找的,谢谢!最后一个问题,你可以给我一个网页或其他资源,我可以了解更多关于正则表达式? – JuanS

0

必须(前添加\因为(在正则表达式是特殊的群体性格

的正则表达式pattren是: ^创建(\ d + \ d +)