Regex inverse matching on specific string?

北慕城南 提交于 2019-12-01 20:53:56

问题


I would like to match the following

  • com.my.company.moduleA.MyClassName
  • com.my.company.moduleB.MyClassName
  • com.my.company.anythingElse.MyClassName

but not the following

  • com.my.company.core.MyClassName

My current simple regex pattern is :

Pattern PATTERN_MODULE_NAME = Pattern.compile("com\\.my\\.company\\.(.*?)\\..*")

Matcher matcher = PATTERN_MODULE_NAME.matcher(className);
if (matcher.matches()) {
    // will return the string inside the parentheses (.*?)
    return matcher.group(1);
}

So, basically, how can i match everything else, but not a specific string, which is the string core in my case.

Please share your ideas on how to achieve that in Java ?

Thank you !


回答1:


You can use the following regex:

^com\\.my\\.company\\.(?!core).+?\\.MyClassName$



回答2:


Perhaps a regex is not the clearest way to write this.

if (className.startsWith("com.my.company.") 
    && !className.startsWith("com.my.company.core.")) {

}

This is fair clear what it does, and you might find it is faster. ;)



来源:https://stackoverflow.com/questions/6263923/regex-inverse-matching-on-specific-string

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