Java 正则表达式从JDBCURL查找主机名

Java 正则表达式从JDBCURL查找主机名,java,regex,Java,Regex,我对regex不熟悉。我想使用正则表达式从postgreSQL jdbc URL检索主机名。 假设postgreSQL url是jdbc:postgresql://production:5432/dbname。我需要检索“production”,即主机名。我想尝试使用正则表达式,而不是Java split函数。我试过了 Pattern PortFinderPattern = Pattern.compile("[//](.*):*"); final Matcher match = PortFind

我对regex不熟悉。我想使用正则表达式从postgreSQL jdbc URL检索主机名。 假设postgreSQL url是
jdbc:postgresql://production:5432/dbname
。我需要检索“production”,即主机名。我想尝试使用正则表达式,而不是Java split函数。我试过了

Pattern PortFinderPattern = Pattern.compile("[//](.*):*");
final Matcher match = PortFinderPattern.matcher(url);
if (match.find()) {
    System.out.println(match.group(1));
}
但它匹配从主机名到结尾的所有字符串。请帮帮我

Pattern PortFinderPattern = Pattern.compile(".*:\/\/([^:]+).*");
应该足够可靠地找到它。虽然这可能是一个更好的正则表达式:


不分组的正则表达式:

"(?<=//)[^:]*"

(?您的正则表达式中有一些错误:

[/]
-这只是一个字符,因为
[]
标记了一个字符类,因此它不会完全匹配
/
。要匹配它,您需要这样编写:
[/][/]
\/\/

(.*)
-这会将所有字符匹配到行尾。如果要一直到某个字符,则需要更加具体。例如,您可以通过获取所有非冒号的字符转到冒号,如下所示:
([^:]*)

:*
-这使得冒号是可选的。我想你忘了在冒号后面加一个点(每个字符),就像这样:
:*

下面是您的正则表达式更正:
\/\/([^:]*):.*

希望这有帮助

顺便说一句,如果生产后端口号是可选的(:5432),那么我建议使用以下正则表达式:
\/\/([^/]*)(?:\d+)\/

要捕获Oracle和MySQL JDBC URL变体及其怪癖(例如,Oracle允许使用
@
而不是
/
甚至
@/
),我使用此regexp获取主机名:
[/@+([^:/@++)([:/+++$)
,然后主机名位于组1中

代码,例如

String jdbcURL = "jdbc:oracle:thin:@//hostname:1521/service.domain.local";
Pattern hostFinderPattern = Pattern.compile("[/@]+([^:/@]+)([:/]+|$)");
final Matcher match = hostFinderPattern.matcher(jdbcURL);
if (match.find()) {
  System.out.println(match.group(1));
}
这适用于所有这些URL(和其他变体):

这是假设

  • 主机名在
    /
    @
    之后,或两者的组合之后(单个
    /
    也可以,但我认为JDBC不允许这样)

  • 主机名之后是
    /
    ,或字符串的结尾

请注意,
+
是贪婪的,这对于中间的一个特别重要

String jdbcURL = "jdbc:oracle:thin:@//hostname:1521/service.domain.local";
Pattern hostFinderPattern = Pattern.compile("[/@]+([^:/@]+)([:/]+|$)");
final Matcher match = hostFinderPattern.matcher(jdbcURL);
if (match.find()) {
  System.out.println(match.group(1));
}
jdbc:oracle:thin:@//hostname:1521/service.domain.local
jdbc:oracle:thin:@hostname:1521/service.domain.local
jdbc:oracle:thin:@hostname/service.domain.local
jdbc:mysql://localhost:3306/sakila?profileSQL=true
jdbc:postgresql://production:5432/dbname
jdbc:postgresql://production/
jdbc:postgresql://production