R:gsub/仅替换关键字出现后的那些出现 [英] R: gsub/replace only those occurrences following a keyword occurrence
问题描述
我只想替换出现在特定关键字/模式之后而不是之前的字符串.换句话说,在第一次出现关键字模式之前,什么也不做,然后在该关键字模式的右边开始gsub.见下文:
I only want to replace string occurrences that follow a particular keyword/pattern and not before. in other words, do nothing until the first occurrence of the keyword-pattern, and then start to gsub to the right of that keyword-pattern. See below:
gsub("\\[|\\]", "", "ab[ cd] ef keyword [ gh ]keyword ij ")
实际结果: "ab cd ef关键字gh关键字ij"
Actual results: "ab cd ef keyword gh keyword ij "
所需结果: "ab [cd] [] [asfg]]] ef关键字gh关键字ij"
Desired results: "ab[ cd] [][asfg] ]] ef keyword gh keyword ij "
[已编辑以修复结果.我不想删除关键字"]
推荐答案
您可以使用\G
在关键字后获取连续的匹配项.使用\K
忘记匹配的内容,并匹配以下[
或]
以替换为空字符串.
You might use \G
to get continous matches after keyword. Use \K
to forget what was matched and match the following [
or ]
to be replaced with an empty string.
(?:^.*?keyword\b|\G(?!^))[^\[\]]*\K[\[\]]
部分
-
(?:
非捕获组-
^.*?keyword
匹配直到第一个关键字 -
|
或 -
\G(?!^)
在上一场比赛的末尾断言位置,而不是在开始连续比赛的末尾断言
(?:
Non capturing group^.*?keyword
Match until the first keyword|
Or\G(?!^)
Assert position at the end of previous match, not at the start to get continuous matches
您的代码可能看起来像
gsub("(?:^.*?keyword\\b|\\G(?!^))[^\\[\\]]*\\K[\\[\\]]", "", "ab[ cd] ef keyword [ gh ]keyword ij ", perl=T)
请注意,对于类似Perl的正则表达式,请最后使用
perl=T
.Note to use
perl=T
at the end for Perl-like regular expressions.这篇关于R:gsub/仅替换关键字出现后的那些出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-