只替换字符串中第一次出现的单词 [英] Replacing only the first occurrence of a word in a string

查看:54
本文介绍了只替换字符串中第一次出现的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在正则表达式方面遇到了一些问题,主要是因为我认为我能找到的信息不是专门针对 powershell 的,而且我尝试过的所有示例要么出错,要么没有按预期工作.我试图用另一个词替换字符串中第一次出现的词,但不替换该词的任何其他出现.以字符串为例:

I am having some issues with regular expression mainly because I think the information I can find is not specifically for powershell and all the samples I have tried either error or don't work as intended. I am trying to replace the first occurrence of a word in a string with another word but not replace any other occurrences of that word. for an example take the string:

我叫鲍勃,她叫莎拉.

我想用 baby 替换第一次出现的 name 所以结果字符串是

I would like to replace the first occurrence of name with baby so the resulting string would be

我的宝贝叫鲍勃,她叫莎拉.

我一直在 https://regex101.com/ 尝试构建并查看被选为我去了,但正如我所说,这些都没有正则表达式的 powershell 风味.因为我可以关闭 global 标志,它似乎选择了第一次出现但不在 powershell 中.所以我真的不知道从哪里开始所有在这一点上真正有的是选择所有出现的词 namewith:

I have been working in https://regex101.com/ to try to build and see what is selected as I go but as I said none of these have a powershell flavor of regex. In that I can just turn off the global flag and it seems to select the first occurrence but not in powershell. So I am really at a loss of where to begin all really have at this point is selecting all occurrences of the word namewith:

$test = "My name is Bob, her name is Sara."
$test -replace 'name', 'baby'

推荐答案

您可以捕捉前后的所有内容并替换它:

You could capture everything bevore and behind and replace it:

'My name is Bob, her name is Sara.' -replace '(.*?)name(.*)', '$1baby$2'

这篇关于只替换字符串中第一次出现的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆