使用模式进行 gsub 的方法

huangapple go评论77阅读模式
英文:

How to gsub using patterns

问题

我有一个名为X的列表,其中元素名称如下:

down_PK56c-t_S5_L001.clones_IGH

我想要将元素重命名为类似这样:

PK56c-t

如何使用gsub来实现这个目标?
我尝试过以下代码,但它没有成功:

gsub(".*[down_]([^.]+)[.].*", "\\1", "down_PK56c-t_S5_L001.clones_IGH")

非常感谢!

英文:

I have a list X with element names like this

down_PK56c-t_S5_L001.clones_IGH

I want to rename the elements to be something like this

PK56c-t

how can I do it using gsub?
I tried this and it did not work :/

gsub(".*[down_]([^.]+)[.].*", "\\1", "down_PK56c-t_S5_L001.clones_IGH")

thanks a lot

答案1

得分: 1

你需要在这里使用 sub,就像下面的代码一样:

sub(".*down_([^_]+).*", "\", text)

查看正则表达式演示

细节

  • .* - 任意零个或多个字符,尽可能少
  • down_ - 字面字符串
  • ([^_]+) - 第一组(\1指的是此组文本):一个或多个不是下划线的字符
  • .* - 任意零个或多个字符,尽可能少
英文:

You need a sub here like

sub(".*down_([^_]+).*", "\", text)

See the regex demo.

Details:

  • .* - any zero or more chars as possible
  • down_ - a literal string
  • ([^_]+) - Group 1 (\1 refers to this group text): one or more chars other than an underscore
  • .* - any zero or more chars as possible

答案2

得分: 1

我们还可以使用具有后顾之策的“extract”策略:

library(stringr)

string <- "down_PK56c-t_S5_L001.clones_IGH"
str_extract(string, pattern = "(?<=down_)[^_]+")

[1] "PK56c-t"
英文:

We can also use an extract strategy with a look behind:

library(stringr)

string &lt;- &quot;down_PK56c-t_S5_L001.clones_IGH&quot;
str_extract(string, pattern = &quot;(?&lt;=down_)[^_]+&quot;)

[1] &quot;PK56c-t&quot;

</details>



huangapple
  • 本文由 发表于 2023年3月7日 04:57:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定