Reputation: 140
What will be the regular expression forbelow jdbc urls to find the databaseName. Output will be "ab_cd_e".
String jdbcUrl="jdbc:sqlserver://abc.com:1440;instanceName=MSSQLSERVER2019;integratedSecurity=false;databaseName=ab_cd_e";
String jdbcUrl="jdbc:sqlserver://abc.com:1440;instanceName=MSSQLSERVER2019;databaseName=ab_cd_e;integratedSecurity=false";
I have tried:
Pattern pattern = Pattern.compile("^(;databaseName=)(.*?)([;])", Pattern.CASE_INSENSITIVE);
Upvotes: 1
Views: 1638
Reputation: 18641
Use
;databaseName=([^;]*)
See proof
Explanation
EXPLANATION
--------------------------------------------------------------------------------
;databaseName= ';databaseName='
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^;]* any character except: ';' (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
import java.util.regex.*;
class TestClass
{
public static void main (String[] args) throws java.lang.Exception
{
final String regex = ";databaseName=([^;]*)";
final String string = "jdbc:sqlserver://abc.com:1440;instanceName=MSSQLSERVER2019;databaseName=ab_cd_e;integratedSecurity=false\n" + "jdbc:sqlserver://abc.com:1440;instanceName=MSSQLSERVER2019;integratedSecurity=false;databaseName=ab_cd_e";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Name: " + matcher.group(1));
}
}
}
Prints
Name: ab_cd_e Name: ab_cd_e
Upvotes: 1
Reputation: 994
from here How to extract a substring using regex
String mydata = "jdbc:sqlserver://abc.com:1440;instanceName=MSSQLSERVER2019;databaseName=ab_cd_e;integratedSecurity=false";
Pattern pattern = Pattern.compile("databaseName=(\w+)(|;$)");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
output:
ab_cd_e
Upvotes: 0
Reputation: 3433
You just need to extract the string between the parts databaseName=
and ;
or $
end of line. To achieve this you can use a positive lookahead (?=;|$)
and a positive lookbehind (?<=databaseName=)
Hence, the regex (?<=databaseName=)\\w+(?=;|$)
gives you ab_cd_e
Try this:
Pattern pattern = Pattern.compile("(?<=databaseName=)\\w+(?=;|$)", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(jdbcUrl);
if (matcher.find())
System.out.println(matcher.group());
Upvotes: 2