Parse through string for known section
I was wondering what the best way to go about parsing "HOST" names out of oracle connection strings. Here is an example connection string:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)))
And I have it in a String
. What is the best way to get "MyHost" returned. Also would be nice if it worked for double connection strings, example:
((Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost1)(PORT=MyPort1)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID1))))(Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost2)(PORT=MyPort2)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID2)))))
Would return "MyHost1" and "MyH开发者_运维问答ost2".
Trying to write a method that takes in a connection string and spits out the host/hosts in an array list of strings.
Using a regular expression like this should work: \(HOST=([^)]+)\)
.
Don't forget to double the backslashes in Java String
literals:
Pattern hostPattern = Pattern.compile("\\(HOST=([^)]+)\\)");
Create a Matcher
from that Patttern
and your input string using matcher()
and call find()
until it returns false
. Use group(1)
to get the host names:
Matcher m = hostPattern.matcher(input);
while (m.find()) {
System.out.println(m.group(1));
}
Extending Joachim's idea (and I haven't used ArrayLists in a while so it may not be totally correct):
public List<String> getHosts(String conString) {
List<String> conns = new ArrayList<String>()
Pattern hostPattern = Pattern.compile("\\(HOST=([^)]+)\\)");
Matcher m = hostPattern.matcher(conString);
while(m.find()) {
conns.add(m.group(1));
}
return conns;
}
EDIT: Thanks for the fixes Bart!
The regular expression \(HOST=(.*?)\) will match the section "(HOST=MyHost1)" and "(HOST=MyHost2)" as two groups containing "MyHost1" and "MyHost2" respectively.
Cheers,
Ed
精彩评论