Search Simultaneous Special Characters in a string using PowerShell - string

I am trying to work on an issue where if a string has multiple "special characters " in a string how do I replace that with a single character.
For Example: -
$a = "INC0010347~INC0010348~~INC0010349"
$a = $a.Replace("~~","~")
$a
Result 1: - "INC0010347~INC0010348~INC0010349"
In the above case a Replace function would work if the characters are 2 in number. However anything more than 2 will fail.. as in the below:
$a = "INC0010347~INC0010348~~~INC0010349"
$a = $a.Replace("~~","~")
$a
Result 2: - "INC0010347~INC0010348~~INC0010349"
I am working on a script that would help me do this dynamically irrespective of the number of special characters (in this case tilde(~)) the result should be
Result 1: - "INC0010347~INC0010348~INC0010349"

Just add the + Quantifier:
$a = "INC0010347~INC0010348~~~INC0010349"
$a -replace '~+','~'
Or:
[regex]::Replace($a,'~+','~')
Note:
instead of using string.Replace method e.g. $a.Replace('~+','~') which will not work, use -replace or [regex]::Replace which support Regex
See:
Quantifiers in Regular Expressions

Related

Drop (substract) last n characters from a variable string length

I need to drop (or replace to nothing) last n characters of a string in powershell code. The variant could be with substraction string form a string (didn't find my answer).
I have something like this (string):
something/something/../lastsomething/NAME
where NAME is a variable text I can extract beforehand and manipulate ($name or $name.length). And the whole string can be counted - $string.length.
How can I substract this NAME from a string ($string)? I've searched many ways, including trim,replace,substring - but all of these mostly work with static words or regex, or with the begining of a string.
I need to get this:
something/something/../lastsomething
I've tried even such constructions:
$string.split('($NAME)')[0]
and
$string.split('[string]($NAME)')[0]
and other with get-AD* functions with join to bypass the strings, but nothing did the trick.
A simple solution is take the substring from beginning (0) to the last occurence of /.
$t = 'something/something/../lastsomething/NAME'
$t.Substring(0, $t.LastIndexOf('/'))
EDIT from your comment the real question is how to get
-replace '($_.Name)',' '
working. The single quotes don't expand variables - so use double quotes.
To force evaluation of $_.Name you have to enclose it with $()
-replace "/$($_.Name)"
With an unknown last element /Name
> $String = 'something/something/../lastsomething/NAME'
> $String.Split('/')[-1]
NAME
> $string = $string -replace "/$($String.Split('/')[-1])"
> $string
something/something/../lastsomething
A much simpler solution is :
> Split-Path $string
something\something\..\lastsomething
> Split-Path $string -Leaf
NAME
but it changes slashes to backslashes
You can replace it with '' (nothing ... empty string) and because -replace works with regular expressions you can make sure that you only get a "match" at the end of the string like this:
$var = '/NAME'
'something/Name/something/../lastsomething/NAME' -replace "$var$",''

Powershell removing characters from string up to last separator

I have a string
Projects\TestEnvironment\11111xx\1111111
and need to get 1111111 from it. What I'm doing now is:
$name = $dir.Substring($dir.IndexOf('\')+1)
where $dir is my string, however it only removes up to first string, is it possible to change direction?
What about using split-path?
$string = 'Projects\TestEnvironment\11111xx\1111111'
Split-Path $string -Leaf
returns 1111111.
Note the -Leaf parameter indicates that this cmdlet returns only the last item or container in the path.
#Robin's answer is good if the string is always a path (separated with "\"); in the general case, where the delimiter may be a different character, you can use
$string = "This-is-a-string-with-delimiters"
$lastword = ($string -split "-")[-1]
The -split operator defaults to splitting on a space, but will split on any character you choose to pass it, returning an array of strings, each string being the material before/between/after delimiters - in the example above, each word would be in a separate string in the array. Negative subscripts to an array count from the end of the array rather than the start, and are 1-origin rather than 0-origin - so $x[-1] is the last element of the array $x.
This technique also works on paths;
$path = "C:\Users\JSmith\Documents\Resume.doc"
$filename = ($path -split "\\")[-1]
will give you $filename -eq Resume.doc. Note that the delimiter passed to -split in this case is escaped, because the delimiter can be a regular expression, and the backslash ("\") is meaningful in regular expressions (it's the character that indicates that another meaningful character is to be "escaped", or its meaning ignored).
other solution
('Projects\TestEnvironment\11111xx\1111111' -split '\\')[-1]
or
'Projects\TestEnvironment\11111xx\1111111'.Split('\')[-1]

perl extract numbers from string, edit, put back into string at their original position

I'm trying to edit the numbers in a string and put it back in the same place as they have been before.
Example:
$string = "struct:{thin:[[75518103,75518217],[75518338,75518363],[75532810,75533910],],thick:[[75518363,75518424],[75521257,75521463],],}";
I need to edit the numbers, but want to keep the rest of the string at it is. Additionally the number of brackets can vary.
Until now I split the string at "," with
#array = split (',',$string);
and extracted the numbers for editing with
foreach (#array) {
$_ =~ s/\D//g;
$_ = $number - $_;
}
now I want to put the numbers back in their original place in the string, but I don't know how.
Somehow I hope there is a better way to edit the numbers in the string without splitting it and extracting the numbers. Hope you can help me
You could use a regular expression substitution with the /e flag, search for long numbers and run Perl code in the substitution part.
use strict;
use warnings;
use feature 'say';
my $number = 100_000_000;
my $string = "struct:{thin:[[75518103,75518217],[75518338,75518363],[75532810,75533910],],thick:[[75518363,75518424],[75521257,75521463],],}";
$string =~ s/(\d+)/{$number - $1}/eg;
say $string;
__END__
struct:{thin:[[24481897,24481783],[24481662,24481637],[24467190,24466090],],thick:[[24481637,24481576],[24478743,24478537],],}
If there are no other numbers in the string, that would work. In case there is more logic involved, you can also move it into a subroutine and just call that in the substitution.
sub replace {
return $_ % 2 ? $_ * 2 : $_ / 4;
}
$string =~ s/(\d+)/{replace($1)}/eg;
You might also need to revise the search pattern to be a bit more precise.
I just found the evaluation modifier for regex! I now did it with
$string =~ s/([0-9]+)/$number-$1/eg;
and it worked!

Removing spaces from a variable input using PowerShell 4.0

I've tried a few things already but they don't seem to work for some reason.
Basically what I'm attempting to do is have a user input a value using the
"Read-host" cmdlet, then strip it of any spaces.
I tried:
$answer = read-host
$answer.replace(' ' , '""')
And:
$answer = read-host
$answer -replace (' ')
I'm probably missing something really obvious, but if anyone could help me out or show me an easier way to achieve this I would appreciate it.
I was going to pipeline the variable to a command and strip it in that fashion, but none of the examples I've seen work, although they look much easier.
The Replace operator means Replace something with something else; do not be confused with removal functionality.
Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace(), nor -replace modifies the original variable.
To remove all spaces, use 'Replace any space symbol with empty string'
$string = $string -replace '\s',''
To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use
$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '
or the more native System.String method
$string = $string.Trim()
Regexp is preferred, because ' ' means only 'spacebar' symbol, and '\s' means 'spacebar, tab and other space symbols'. Note that $string.Replace() does 'Normal' replace, and $string -replace does RegEx replace, which is more heavy but more functional.
Note that RegEx have some special symbols like dot (.), braces ([]()), slashes (\), hats (^), mathematical signs (+-) or dollar signs ($) that need do be escaped. ( 'my.space.com' -replace '\.','-' => 'my-space-com'. A dollar sign with a number (ex $1) must be used on a right part with care
'2033' -replace '(\d+)',$( 'Data: $1')
Data: 2033
UPDATE: You can also use $str = $str.Trim(), along with TrimEnd() and TrimStart(). Read more at System.String MSDN page.
You're close. You can strip the whitespace by using the replace method like this:
$answer.replace(' ','')
There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).
You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.
#Note there are spaces at the beginning and end
Write-Host " ! This is a test string !%^ "
! This is a test string !%^
#Strips standard whitespace
Write-Host " ! This is a test string !%^ ".Trim()
! This is a test string !%^
#Strips the characters I specified
Write-Host " ! This is a test string !%^ ".Trim('!',' ')
This is a test string !%^
#Now removing ^ as well
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^')
This is a test string !%
Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')
This is a test string
#Powershell even casts strings to character arrays for you
Write-Host " ! This is a test string !%^ ".Trim('! ^%')
This is a test string
TrimStart and TrimEnd work the same way just only trimming the start or end of the string.
You can use:
$answer.replace(' ' , '')
or
$answer -replace " ", ""
if you want to remove all whitespace you can use:
$answer -replace "\s", ""
If the string is
$STR = 'HELLO WORLD'
and you want to remove the empty space between 'HELLO' and 'WORLD'
$STR.replace(' ','')
replace takes the string and replaces white space with empty string (of length 0), in other words the white space is just deleted.

string alignment in perl / match alignment

I have two strings $dna1 and $dna2. Print the two strings as concatenated, and then print the second string lined up over its copy at the end of the concatenated strings. For example, if the input
strings are AAAA and TTTT, print:
AAAATTTT
TTTT
this is a self exercise question .. not a homework ,
i tried using index
#!/usr/bin/perl -w
$a ='AAAAAAAAAATTTTTTTTT';
$b ='TTTTTTTTTT';
print $a,"\n";
print ''x index($a,$b),$b,"\n";
but it is not working as needed .help please
Start by checking what index($a,$b) is returning... Perhaps you should pick a $b that's actually in $a!
Then realise that concatenating 10 instances of an empty string is an empty string, not 10 spaces.
This is a fun little exercise. I did this:
perl -lwe'$a="AAAA"; $b="TTTT"; $c = $a.$b; $i = index($c,$b) + length($b);
print $c; printf "%${i}s\n", $b;'
AAAAAAATTTT
TTTT
Note that generally speaking, using the variable names $a through $c is a bad idea, and only acceptable here because it is a one-liner. $a and $b are also reserved variable names used with sort.

Resources