问题
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?
回答1:
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"
回答2:
Don't use find
, use matches
.
回答3:
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());
}
来源:https://stackoverflow.com/questions/7707417/verifying-that-a-regular-expression-matches