R正则表达式提取相似的词,但其中一个有连字符
R regex extract similar words but one has hyphen
我有以下数据框:
species size_description
1 "some text Small some text"
2 "some text small-med some text"
3 "some text Med. some text"
4 "some text medium some text"
5 "some text med-large some text"
6 "some text large some text"
我想写一个正则表达式来捕获尺寸描述字段中的尺寸,所以它看起来像这样:
species size_description newSize
1 "some text Small some text" "Small"
2 "some text small-med some text" "small-med"
3 "some text Med. some text" "Med."
4 "some text medium some text" "medium"
5 "some text med-large some text" "med-large"
6 "some text large some text" "large"
我试过这样做:
size_regex = paste(
"[Ss]{1}mall",
"[Mm]{1}ed\.*i*u*m*",
"[Mm]{1}ed\.*i*u*m*-*\s*[Ll]{1}arge", #doesnt work
"[Ss]{1}mall-*\s*[Mm]{1}ed\.*i*u*m*", #doesnt work
"[Ll]{1}arge",
sep = "|"
)
df$newSize = str_extract(df$size_description, age_regex)
但是,它不能区分带连字符的。例如,对于物种 2,它记录为 "small" 而不是 "small-med".
我如何编写在 R 中执行此操作的正则表达式?我更喜欢 stringr 包,但任何东西都可以。
请注意,我在正则表达式中保留完整单词选项的原因是某些描述使用完整单词。例如,有些可能是 "small-medium" 而其他的只是 "small-med".
我认为这个正则表达式将满足您提到的条件
(\S*(?:[Ss]mall|[Ll]arge|[Mm]edium|Med[.])\S*)
我有以下数据框:
species size_description
1 "some text Small some text"
2 "some text small-med some text"
3 "some text Med. some text"
4 "some text medium some text"
5 "some text med-large some text"
6 "some text large some text"
我想写一个正则表达式来捕获尺寸描述字段中的尺寸,所以它看起来像这样:
species size_description newSize
1 "some text Small some text" "Small"
2 "some text small-med some text" "small-med"
3 "some text Med. some text" "Med."
4 "some text medium some text" "medium"
5 "some text med-large some text" "med-large"
6 "some text large some text" "large"
我试过这样做:
size_regex = paste(
"[Ss]{1}mall",
"[Mm]{1}ed\.*i*u*m*",
"[Mm]{1}ed\.*i*u*m*-*\s*[Ll]{1}arge", #doesnt work
"[Ss]{1}mall-*\s*[Mm]{1}ed\.*i*u*m*", #doesnt work
"[Ll]{1}arge",
sep = "|"
)
df$newSize = str_extract(df$size_description, age_regex)
但是,它不能区分带连字符的。例如,对于物种 2,它记录为 "small" 而不是 "small-med".
我如何编写在 R 中执行此操作的正则表达式?我更喜欢 stringr 包,但任何东西都可以。
请注意,我在正则表达式中保留完整单词选项的原因是某些描述使用完整单词。例如,有些可能是 "small-medium" 而其他的只是 "small-med".
我认为这个正则表达式将满足您提到的条件
(\S*(?:[Ss]mall|[Ll]arge|[Mm]edium|Med[.])\S*)