特定字符串上的正则表达式反向匹配?

时间:2022-09-13 16:34:43

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 ?

请分享一下如何在Java中实现这一目标的想法?

Thank you !

谢谢 !

2 个解决方案

#1


6  

You can use the following regex:

您可以使用以下正则表达式:

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

#2


5  

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. ;)

这很清楚它的作用,你可能会发现它更快。 ;)

#1


6  

You can use the following regex:

您可以使用以下正则表达式:

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

#2


5  

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. ;)

这很清楚它的作用,你可能会发现它更快。 ;)