Stealthmatt
Stealthmatt

Reputation: 33

PowerShell -replace to get string between two different characters

I am current using split to get what I need, but I am hoping I can use a better way in powershell.

Here is the string:

server=ss8.server.com;database=CSSDatabase;uid=WS_CSSDatabase;pwd=abc123-1cda23-123-A7A0-CC54;Max Pool Size=5000

I want to get the server and database with out the database= or the server=

here is the method I am currently using and this is what I am currently doing:

$databaseserver = (($details.value).split(';')[0]).split('=')[1]
$database = (($details.value).split(';')[1]).split('=')[1]

This outputs to:

ss8.server.com
CSSDatabase

I would like it to be as simple as possible.

Thank you in advance

Upvotes: 1

Views: 6056

Answers (2)

user6811411
user6811411

Reputation:

Another solution with a RegEx and named capture groups, similar to Wiktor's Matching Approach.

$s = 'server=ss8.server.com;database=CSSDatabase;uid=WS_CSSDatabase;pwd=abc123-1cda23-123-A7A0-CC54;Max Pool Size=5000'
$RegEx = '^server=(?<databaseserver>[^;]+);database=(?<database>[^;]+)'
if ($s -match $RegEx){
    $Matches.databaseserver
    $Matches.database
}

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

Replacing approach

You may use the following regex replace:

$s = 'server=ss8.server.com;database=CSSDatabase;uid=WS_CSSDatabase;pwd=abc123-1cda23-123-A7A0-CC54;Max Pool Size=5000'
$dbserver = $s -replace '^server=([^;]+).*', '$1'
$db = $s -replace '^[^;]*;database=([^;]+).*', '$1'

enter image description here

The technique is to match and capture (with (...)) what we need and just match what we need to remove.

Pattern details:

  • ^ - start of the line
  • server= - a literal substring
  • ([^;]+) - Group 1 (what $1 refers to) matching 1+ chars other than ;
  • .* - any 0+ chars other than a newline, as many as possible

Pattern 2 is almost the same, the capturing group is shifted a bit to capture another detail, and some more literal values are added to match the right context.

Note: if the values you need to extract may appear anywhere in the string, replace ^ in the first one and ^[^;]*; pattern in the second one with .*?\b (any 0+ chars other than a newline, as few as possible followed with a word boundary).

Matching approach

With a -match, you may do it the following way:

$s -match '^server=(.+?);database=([^;]+)'

The $Matches[1] will contain the server details and $Matches[2] will hold the DB info:

Name                           Value
----                           -----
2                              CSSDatabase
1                              ss8.server.com
0                              server=ss8.server.com;database=CSSDatabase

Pattern details

  • ^ - start of string
  • server= - literal substring
  • (.+?) - Group 1: any 1+ non-linebreak chars as few as possible
  • ;database= - literal substring
  • ([^;]+) - 1+ chars other than ;

Upvotes: 2

Related Questions