finding a string inside a string using wildcards (Powershell) - powershell

I have a long string:
lqmdkqsdkdqBEGIN{dsqldqsazadksqld},dqsdlqsm},dlqsmd
I want to substract BEGIN{dsqldqsazadksqld} from it using wildcards BEGIN{*} , but not B̶E̶G̶I̶N̶{̶d̶s̶q̶l̶d̶q̶s̶a̶z̶a̶d̶k̶s̶q̶l̶d̶}̶,̶d̶q̶s̶d̶l̶q̶s̶m̶}̶
how do i achieve this with Powershell ?

Use regex instead of wildcard matching:
PS ~> 'lqmdkqsdkdqBEGIN{dsqldqsazadksqld},dqsdlqsm},dlqsmd' -replace '^.*(BEGIN\{[^}]+\}).*$','$1'
BEGIN{dsqldqsazadksqld}
The regular expression pattern ^.*(BEGIN\{[^}]+\}).*$ describes:
^ # start of string
.* # 0 or more of any characters
( # start capture group 1
BEGIN\{ # match literal string `BEGIN{`
[^}]+ # 1 or more non-`}` characters
\} # a literal `}`
) # end capture group
.* # 0 or more of any characters
$ # end of string
The $1 in the substitution string is replaced with the value captured by the group described in the pattern.

Related

replace regex value in powershell

From the below line:
[1;32mget[0m /dir/dir/dir {} [oiid:197,uiid:7522] [32m200[0m (676ms)
convert it to:
get /dir/dir/dir {} [oiid:197,uiid:7522] 200 (676ms)
any suggestions on regex please the value 200 can be any number and the value get can be any http method.
I have tried
$_.replace("[[\d+m]","").replace('[[1;\d+m]',"").replace('[[\d+]m]',"")
} | Set-Content $newfilepath```
You can do the following using -replace operator and a regex:
$string = '[1;32mget[0m /dir/dir/dir {} [oiid:197,uiid:7522] [32m200[0m (676ms)'
$string -replace '\[\d.*?m'
\[ matches [ and note that it needs to be escaped for literal match because [ is special to regex. \d is a digit. .*? matches as few characters as possible until m is matched.
The String class Replace() method does not support regex. So you cannot use regex expressions like \d inside.

Trim Powershell OutPut

Requirement is to trim the Output. Retain only the output quoted within double quotes from Name and remove/avoid the earlier lines/characters
From:
$R.Output = \\GBVServer1\root\cimv2:Win32_Group.Domain="Contoso",Name="Domain Users"
$R.Output = \\GBVServer1\root\cimv2:Win32_SystemAccount.Domain="GBVServer1",Name="INTERACTIVE"
To:
$R.Output = Domain Users
$R.Output = INTERACTIVE
Could somebody assist with the powershell switch to be used?
You can do this with regex to capture only the Name part between the quotes for these strings:
$regex = [regex]'(?i)Name="([^,]+)"'
$string = '\\GBVServer1\root\cimv2:Win32_Group.Domain="Contoso",Name="Domain Users"'
$R.Output = $regex.Match($string).Groups[1].Value # --> Domain Users
$string = '\\GBVServer1\root\cimv2:Win32_SystemAccount.Domain="GBVServer1",Name="INTERACTIVE"'
$R.Output = $regex.Match($string).Groups[1].Value # --> INTERACTIVE
Regex details:
Name=" Match the characters “Name="” literally
( Match the regular expression below and capture its match into backreference number 1
[^,] Match any character that is NOT a “,”
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
" Match the character “"” literally
The (?i) makes the match case-insensitive

How to replace character in Powershell with initial character + a space

Hopefully this question isn't already answered on the site. I want to replace every number in a string with that number and a space. So here's what I have right now:
"31222829" -replace ("[0-9]","$0 ")
The [0-9] looks for any numbers, and replaces it with that character and the space. However, it doesn't work. I saw from another website to use $0 but I'm not sure what it means.The output I was looking for was
3 1 2 2 2 8 2 9
But it just gives me a blank line. Any suggestions?
LardPies
This probably isn't the right way to do it, but it works.
("31222829").GetEnumerator() -join " "
The .GetEnumerator method iterates over each character in the string
The -join operator will then join all of those characters with the " " space
tl;dr
PS> "31222829" -replace '[0-9]', '$& '
3 1 2 2 2 8 2 9
Note that the output string has a trailing space, given that each digit in the input ([0-9]) is replaced by itself ($&) followed by a space.
As for what you tried:
"31222829" -replace ("[0-9]","$0 ")
While enclosing the two RHS operands in (...) doesn't impede functionality, it's not really helpful to conceive of them as an array - just enumerate them with ,, don't enclose them in (...).
Generally, use '...' rather than "..." for the RHS operands (the regex to match and the replacement operand), so as to prevent confusion between PowerShell's string expansion (interpolation) and what the -replace operator ultimately sees.
Case in point: Due to use of "..." in the replacement operand, PowerShell's string interpolation would actually expand $0 as a variable up front, which in the absence of a variable expands to the empty string - that is why you ultimately saw a blank string.
Even if you had used '...', however, $0 has no special meaning in the replacement operand; instead, you must use $& to represent the matched string, as explained in this answer.
To unconditionally separate ALL characters with spaces:
Drew's helpful answer definitely works.
Here's a more PowerShell-idiomatic alternative:
PS> [char[]] '31222829' -join ' '
3 1 2 2 2 8 2 9
Casting a string to [char[]] returns its characters as an array, which -join then joins with a space as the separator.
Note: Since -join only places the specified separator (' ') between elements, the resulting string does not have a trailing space.
You can use a regex with positive lookahead to avoid the trailing space. Lookahead and lookbehind are zero-length assertions similar to ^ and $ that match the start/end of a line. The regex \d(?=.) will match a digit when followed by another character.
PS> '123' -replace '\d(?=.)', '$0 '
1 2 3
To verify there's no trailing space:
PS> "[$('123' -replace '\d(?=.)', '$0 ')]"
[1 2 3]

PowerShell Trim bug with String containing "< char >$< repeated char >"?

If I use the Trim() method on a string containing -char-$-repeated char-, e.g. "BL$LA" or "LA$AB", Trim() strips the repeated char after the $ as well.
For example:
$a = 'BL$LA'
$b = $a.Trim("BL$")
returns A not LA, but
$a = 'BM$LA'
$b = $a.Trim("BM$")
returns LA.
Any reason why? Or am I missing something?
The Trim() method removes all characters in the given argument (the string is automatically cast to a character array) from beginning and end of the string object. Your second example only seems to be doing what you want, because the remainder of the string does not have any of the characters-to-be-trimmed in it.
Demonstration:
PS C:\> $a = 'BL$LA'
PS C:\> $a.Trim("BL$")
A
PS C:\> $a = 'LxB$LA'
PS C:\> $a.Trim("BL$")
xB$LA
To remove a given substring from beginning and end of a string you need something like this instead:
$a -replace '^BL\$|BL\$$'
Regular expression breakdown:
^ matches the beginning of a string.
$ matches the end of a string.
BL\$ matches the literal character sequence "BL$".
...|... is an alternation (match any of these (sub)expressions).
If you just want to remove text up to and including the first $ from the beginning of a string you could also do something like this:
$a -replace '^.*?\$'
Regular expression breakdown:
^ matches the beginning of a string.
\$ matches a literal $ character.
.*? matches all characters up to the next (sub)expression (shortest/non-greedy match).

How to escape all special characters in a string (along with single and double quotes)?

E.g:
$myVar="this###!~`%^&*()[]}{;'".,<>?/\";
I am not able to export this variable and use it as it is in my program.
Use q to store the characters and use the quotemeta to escape the all character
my $myVar=q("this###!~`%^&*()[]}{;'".,<>?/\");
$myVar = quotemeta($myVar);
print $myVar;
Or else use regex substitution to escape the all character
my $myVar=q("this###!~`%^&*()[]}{;'".,<>?/\");
$myVar =~s/(\W)/\\$1/g;
print $myVar;
This is what quotemeta is for, if I understand your quest
Returns the value of EXPR with all non-"word" characters backslashed. (That is, all characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings.
Its use is very simple
my $myVar = q(this###!~`%^&*()[]}{;'".,<>?/\\);
print "$myVar\n";
my $quoted_var = quotemeta $myVar;
print "$quoted_var\n";
Note that we must manually escape the last backslash, to prevent it from escaping the closing delimiter. Or you can tack on an extra space at the end, and then strip it (by chop).
my $myVar = q(this###!~`%^&*()[]}{;'".,<>?/\ );
chop $myVar;
Now transform $myVar like above, using quotemeta.
I take the outside pair of " to merely indicate what you'd like in the variable. But if they are in fact meant to be in the variable then simply put it all inside q(), since then the last character is ". The only problem is a backslash immediately preceding the closing delimiter.
If you need this in a regex context then you use \Q to start and \E to end escaping.
Giving Thanks to:
What's between \Q and \E is treated as normal characters, not regexp characters. For example,
'.' =~ /./; # match
'a' =~ /./; # match
'.' =~ /\Q.\E/; # match
'a' =~ /\Q.\E/; # no match
It doesn't stop variables from being interpolated.
$search = '.';
'.' =~ /$search/; # match
'a' =~ /$search/; # match
'.' =~ /\Q$search\E/; # match
'a' =~ /\Q$search\E/; # no match