Verifying that a Regular Expression Matches
I have a regex that, according to what I can tell and to what RegexPal says, does not match the full string I am testing (only its rightmost part). However, matcher.matches()
returns true!
So, what is the most reliable way to determine whether a java.util.regex Matcher actually fully matches a string?
Also, suppose that one wants to use matcher.find()开发者_高级运维 as follows:
if (a match was found)
{
while (matcher.find())
{
// Do whatever
}
]
Is there any way of implementing the "a match was found" condition check?
Don't use find
, use matches
.
matches() returning true would mean there some match. Whether it's the "full" string or not, simply depends on what your regex is. E.g.
"a"
would match all of the following
"a"
"abb"
"bab"
"bba"
if you're looking to match full string, your regex must begin with ^
and end with $
E.g.
"^a$"
would match "a"
, but none of the following
"abb"
"bab"
"bba"
Well, I've never had matches()
not work, but you can use find()
, then use
matcher.start()==0&&matcher.end()==string.length()
I don't think you need the if, because the while(matcher.find())
should check , but if you do...
if(matcher.find()){
do{
//whatever
} while(matcher.find());
}
精彩评论