简体   繁体   English

R:如何使用 stringr 提取子字符串作为输出来变异以字符串模式开头并以数字结尾的字符串列?

[英]R: How to use stringr to extract the substring as the output to mutate a column of strings that begins with a string pattern and end with a number?

I'm creating a small example to be put into mutate().我正在创建一个要放入 mutate() 的小示例。 Not sure why this doesn't work.不知道为什么这不起作用。

> str_extract("rs1234-<b>C</b>","^rs*\\d$")
[1] NA

I'd be great if you can point to my misunderstanding of the language instead of merely providing a solution.如果您能指出我对语言的误解而不是仅仅提供解决方案,我会很棒。 I expect to get "rs1234".我希望得到“rs1234”。

The ^rs*\\d$ regex matches ^rs*\\d$正则表达式匹配

  • ^ - start of string ^ - 字符串的开始
  • rs* - r and zero or more occurrences of s char rs* - r和零次或多次出现的s字符
  • \\d - a digit \\d - 一个数字
  • $ - end of string. $ - 字符串的结尾。

So, your pattern matches strings like rsssss1 , r3 , etc.因此,您的模式匹配rsssss1r3等字符串。

You need你需要

str_extract("rs1234-<b>C</b>", "^rs\\d+")

where ^rs\\d+ matches rs at the start of string and then one or more digits.其中^rs\\d+匹配字符串开头的rs ,然后匹配一位或多位数字。 See this regex demo .请参阅此正则表达式演示

But if I just want the substring in between "rs" and the last number.但是,如果我只想要“rs”和最后一个数字之间的子字符串。 What should I do?我应该怎么办?

You would use rs.*\\d :你会使用rs.*\\d

str_extract("rs1234-<b>C</b>", "rs.*\\d")

where rs.*\\d matches rs , then any zero or more chars other than line break chars as many as possible and then a digit.其中rs.*\\d匹配rs ,然后是尽可能多的除换行符以外的零个或多个字符,然后是一个数字。

NOTE: If you need to match line endings, too, you need to prepend the last pattern with (?s) inline DOTALL modifier.注意:如果你也需要匹配行尾,你需要在最后一个模式前加上(?s)内联 DOTALL 修饰符。

See this regex demo .请参阅此正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R/Stringr 在第 n 次出现“_”后提取字符串并以第一次出现“_”结束 - R/Stringr Extract String after nth occurrence of "_" and end with first occurrence of "_" 使用R中的stringr查找最后一个子字符串后面的剩余字符串 - Use stringr in R to find the remaining string after last substring 如何在r中使用stringr将字符串分为数字和其余字符串? - How do I split strings into number and the remaining string using stringr in r? R,stringr,mutate(我认为)-多个字符串中的多个部分字符串替换 - R, stringr, mutate (I think) - multiple partial string replacements in multiple strings R使用str_extract(stringr)在“_”之间导出一个字符串 - R use str_extract (stringr) to export a string between “_” 如何使用 stringr 从字符串中提取多个重叠的字符串? - how to extract multiple overlapping strings from a string using stringr? 如何使用stringr和regexp从字符串末尾删除空格和数字? - How to use stringr and regexp to remove spaces and digits from end of strings? 如何在 R 中使用 stringr 提取数字 - how can I str_extract number using stringr in R 从R中的字符串中提取带有点子字符串的模式 - extract a pattern with dot substring from a string in R 如何使用stringr从R中的维度字符串中提取高度和宽度? - How to extract height and width from dimensions string in R using stringr?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM