英文:
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 possibledown_
- 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 <- "down_PK56c-t_S5_L001.clones_IGH"
str_extract(string, pattern = "(?<=down_)[^_]+")
[1] "PK56c-t"
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论