Verifying that a Regular Expression Matches

感情迁移 提交于 2019-12-24 17:55:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!