简体   繁体   English

用于花括号的正则表达式数字Java中的花括号({n})

[英]Regex for Curly braces Number Curly brace ({n}) in Java

I am trying to write a simple regex , but i don't know where am I going wrong . 我正在尝试编写一个简单的正则表达式,但是我不知道我要去哪里错了。 I need to check whether a string has a curly brace number curly brace. 我需要检查字符串是否具有大括号数字大括号。

Eg: Consider the string 例如:考虑字符串
Swapstream{2} - true 交换流{2}-是的
Swapstram - false Swapstram-错误

Pattern pattern=Pattern.compile("\\{[0-9]\\}");
Matcher matcher=pattern.matcher(input);
if(matcher.matches())
{\\logic}

Also I tried writing \\d instead of [0-9] , still the string is not matching. 我也尝试写\\ d而不是[0-9],但字符串仍然不匹配。 Please help ! 请帮忙 ! . Thanks 谢谢

You can use: 您可以使用:

Pattern pattern=Pattern.compile("\\{\\d+\\}");
Matcher matcher=pattern.matcher(input);
if(matcher.find()) {
    /// match found
}

ie use \\d+ to allow more than one digit between { and } and more importantly use Matcher.find() instead of Matcher.matches() which expects to match complete input line. 例如,使用\\d+允许{}之间有多个数字,更重要的是使用Matcher.find()而不是Matcher.matches()来匹配完整的输入行。

The matches() method only returns true if the entire string is a match for the regular expression. 仅当整个字符串与正则表达式匹配时, matches()方法才返回true。 You should use the find() method of the Matcher class instead. 您应该改用Matcher类的find()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM