Reputation: 36432
I am new to regex. I would like to retrieve the Hostname from postgreSQL jdbc URL using regex.
Assume the postgreSQL url will be jdbc:postgresql://production:5432/dbname
. I need to retrieve "production", which is the hostname. I want to try with regex and not with Java split function. I tried with
Pattern PortFinderPattern = Pattern.compile("[//](.*):*");
final Matcher match = PortFinderPattern.matcher(url);
if (match.find()) {
System.out.println(match.group(1));
}
But it's matching all the string from hostname till the end.
Upvotes: 2
Views: 5482
Reputation: 639
To capture also Oracle and MySQL JDBC URL variants with their quirks (e.g. Oracle allowing to use @
instead of //
or even @//
), I use this regexp to get the hostname: [/@]+([^:/@]+)([:/]+|$)
Then the hostname is in group 1.
Code e.g.
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));
}
This works for all these URLs (and other variants):
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
This assumes that
The hostname is after //
or @
or a combination thereof (single /
would also work, but I don't think JDBC allows that).
After the hostname either :
or /
or the end of the string follows.
Note that the the +
are greedy, this is especially important for the middle one.
Upvotes: 0
Reputation: 3866
There are some errors in your regex:
[//]
- This is only one character, because the []
marks a character class, so it will not fully match //
. To match it, you need to write it like this: [/][/]
or \/\/
.
(.*)
- This will match all characters to the end of line. You need to be more specific if you want to go till a certain character. For example you could go to the colon by fetching all characters, which are not colons, like this: ([^:]*)
.
:*
- This makes the colon optional. I guess you forgot to put a dot( every character ) after the colon, like this: :.*
.
So here is your regex corrected: \/\/([^:]*):.*
.
Hope this helps.
BTW. If the port number is optional after production (:5432), then I suggest the following regex:
\/\/([^/]*)(?::\d+)?\/
Upvotes: 0
Reputation: 37526
[//]([\\w\\d\\-\\.]+)\:
Should be enough to find it reliably. Though this is probably a better regex:
Upvotes: 0