regex - PowerShell -replace to get string between two different characters -
i current using split need, hoping can use better way in powershell.
here string:
server=ss8.server.com;database=cssdatabase;uid=ws_cssdatabase;pwd=abc123-1cda23-123-a7a0-cc54;max pool size=5000
i want server , database out database= or server=
here method using , doing:
$databaseserver = (($details.value).split(';')[0]).split('=')[1] $database = (($details.value).split(';')[1]).split('=')[1]
this outputs to:
ss8.server.com cssdatabase
i simple possible.
thank in advance
replacing approach
you may use 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'
the technique match , capture (with (...)
) need , match need remove.
pattern details:
^
- start of lineserver=
- literal substring([^;]+)
- group 1 (what$1
refers to) matching 1+ chars other;
.*
- 0+ chars other newline, many possible
pattern 2 same, capturing group shifted bit capture detail, , more literal values added match right context.
note: if values need extract may appear anywhere in string, replace ^
in first 1 , ^[^;]*;
pattern in second 1 .*?\b
(any 0+ chars other newline, few possible followed word boundary).
matching approach
with -match
, may following way:
$s -match '^server=(.+?);database=([^;]+)'
the $matches[1]
contain server details , $matches[2]
hold db info:
name value ---- ----- 2 cssdatabase 1 ss8.server.com 0 server=ss8.server.com;database=cssdatabase
pattern details
^
- start of stringserver=
- literal substring(.+?)
- group 1: 1+ non-linebreak chars few possible;database=
- literal substring([^;]+)
- 1+ chars other;
Comments
Post a Comment