Regex matching on a specific line?

I would like to match the following

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

but not next

  • com.my.company. .MyClassName core

My current simple regex pattern:

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 core string in my case.

Share your ideas on how to achieve this in Java?

Thanks!

+4
source share
2 answers

You can use the following regular expression:

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

Perhaps regex isn't the clearest way to write this.

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

It is fairly clear what he is doing, and you may find that it is faster .;)

+5
source

All Articles