当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 PowerShell 中替换单引号

作者:精品下载站 日期:2024-12-14 16:51:46 浏览:16 分类:玩电脑

在 PowerShell 中替换单引号


使用 PowerShell 字符串 replace() 方法或 replace 运算符将 PowerShell 中的单引号替换为空格或双引号。例如$str.replace("'",'') 将单引号替换为空字符串。

replace() 方法返回一个字符串,其中所有单引号都被替换。

在本文中,我们将讨论如何使用 PowerShell Replace() 方法或 replace 运算符来替换字符串中的单引号。

在PowerShell中使用replace()将单引号替换为空白

PowerShell String 内置 replace() 方法采用两个参数;要搜索的字符串和要替换为找到的文本的字符串。

$str = "'C#','PowerShell','NodeJs'"

# Replace all single quotes with blank 
$str.Replace("'",'')                    

上面的 PowerShell 脚本使用 replace() 方法将字符串中的所有单引号替换为空格或空格。

PowerShell replace() 有 2 个参数:

  1. 要在给定字符串中搜索的子字符串
  2. 找到的文本的替换字符串

PowerShell replace() 方法返回一个新字符串,其中字符串中的所有单引号都被空格替换。

将所有单引号替换为空白的上述脚本的输出是:

[玩转系统] 在 PowerShell 中替换单引号

酷提示:如何在 PowerShell 中使用单引号中的变量!

使用 PowerShell 将单引号替换为双引号

使用 PowerShell replace() 方法,它可以将字符串中的所有单引号替换为双引号。

$str = "'C#','PowerShell','NodeJs'"

# Replace all single quotes with double quotes
$str.Replace("'",'"')

在上面的 PowerShell 脚本中,replace() 方法将所有单引号替换为双引号。它使用单引号作为在字符串中查找的第一个参数,使用第二个参数作为双引号来替换找到的文本。

上述将字符串中的所有单引号替换为双引号的 PowerShell 脚本的输出为:

PS C:\> $str = "'C#','PowerShell','NodeJs'"    

PS C:\> $str.Replace("'",'"') 
"C#","PowerShell","NodeJs"

酷提示:如何使用 PowerShell 将字符串中的所有空格替换为换行符!

在 PowerShell 中使用替换运算符替换单引号

使用 PowerShell 替换运算符,您可以将字符串中的所有单引号替换为空白或双引号。

PowerShell 中的replace 运算符有两个参数:要在字符串中查找的字符串以及找到的文本的替换字符串。

$str = "'C#','PowerShell','NodeJs'"
      
# Replace all single quotes with empty
$str -replace "'", ''     

# Replace all single quotes with double quotes
$str -replace "'", '"'

上面的 PowerShell 脚本使用替换运算符将字符串中的所有单引号替换为空格或空格。

替换运算符有 2 个参数:

  1. 要在字符串中搜索的子字符串
  2. 替换字符串

在第一个示例中,replace 运算符将所有单引号替换为空白,在第二个示例中,它将所有单引号替换为双引号。

上述用于替换字符串中单引号的 Powershell 脚本的输出为:

PS C:\> $str = "'C#','PowerShell','NodeJs'"                                                                             

PS C:\> $str -replace "'", ''                                                                                           
C#,PowerShell,NodeJs

 PS C:\>$str -replace "'", '"'
"C#","PowerShell","NodeJs"

酷提示:如何使用 PowerShell 替换字符串中的双引号!

结论

希望上面关于如何使用 PowerShell Replace() 方法将字符串中的所有单引号替换为空白或双引号的文章对您有所帮助。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯