2

I have string like below;

oradb = Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.87.50)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=testdb)));User Id = john; Password=test;

I want to get only '192.168.87.50' , '1521' , 'testdb' , 'john' from above connection string and put into some textboxes.

I tried to make with regexp and understand that it's not possible with regexp.

How can I do it?

2
  • You could read the ConnectionString in using ConfigurationManager and then load up a System.Configuration.ConnectionStringSettings class and retrieve what you want using Properties from there? Commented Nov 29, 2017 at 17:30
  • @jmb.mage this is winform btw. Also how can i get the specified parameters one by one. Can you please write this as an answer ? Commented Nov 29, 2017 at 17:39

2 Answers 2

2

While there should be a more convenient way, you still can use RegExp for this.
Try this code:

var input =
    "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.87.50)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=testdb)));User Id = john; Password=test;";


var hostRegx = new Regex("HOST\\s*=\\s*(?<host>[^\\)]+)");
var portRegx = new Regex("PORT\\s*=\\s*(?<port>[^\\)]+)");
var dbRegx = new Regex("SERVICE_NAME\\s*=\\s*(?<db>[^\\)]+)");
var userRegx = new Regex("User Id\\s*=\\s*(?<user>[^;]+)");
var passRegx = new Regex("Password\\s*=\\s*(?<pass>[^;]+)");

var host = hostRegx.Match(input).Groups["host"].Value;
var port = portRegx.Match(input).Groups["port"].Value;
var db = dbRegx.Match(input).Groups["db"].Value;
var user = userRegx.Match(input).Groups["user"].Value;
var pass = passRegx.Match(input).Groups["pass"].Value;
Sign up to request clarification or add additional context in comments.

2 Comments

Worked like a charm.
@johntrue thank you. By the way, I'm think my approach can be optimized, maybe with one huge regex
1

You can use connection object to retrieve all these information.

SqlConnection connection = new SqlConnection(connectionString); var dbName = connection.Database;

For server name:

DbConnection connection = new SqlConnection(connectionString); 
var server = connection.DataSource;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.