0

I have to replace the first character in a string. I have a snippet like this:

 if(!([string]::Compare($filestmp.Substring(0,1), "M", $True)))
 {
     echo cos
     $filestmp = $filestmp.Replace('^(.*?)M(.*)', 'Zmodyfikowany  ')
 }

The code doesn't throw any exceptions, and it doesn't work either. The if condition passes, since my echo statement is printed. What am I doing wrong here?

3
  • What are you trying to do ? why do you have a regular expression in your code ? How do your string look before replacing ? and how do you want it after ? Commented Dec 22, 2016 at 15:07
  • 1
    String.Replace() doesn't support regex, use the -replace operator or Regex.Replace() Commented Dec 22, 2016 at 15:12
  • My string looks for example "M log.txt" and I want to receive "Zmodyfikowany log.txt" Commented Dec 22, 2016 at 15:20

2 Answers 2

4

RegEx is overkill.

Use a simple substring:

$filestmp=("Zmodyfikowany" +  $filestmp.SubString(1) )
Sign up to request clarification or add additional context in comments.

Comments

0

Other solution:

$filestmp = "M Log.txt"

# Test equal which ignores case
if ($filestmp.Substring(0,1) -ieq "M")
{
    $filestmp = "'Zmodyfikowany{0}" -f  $filestmp.Substring(1)
}

# Test like which ignores case
if ($filestmp -ilike "M*")
{
    $filestmp = "'Zmodyfikowany{0}" -f  $filestmp.Substring(1)
}

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.