在R中的其他两个字符串之间提取一个字符串 [英] Extracting a string between other two strings in R

查看:53
本文介绍了在R中的其他两个字符串之间提取一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种简单的方法来提取出现在两个已知子字符串之间的未知子字符串(可以是任何东西).例如,我有一个字符串:

I am trying to find a simple way to extract an unknown substring (could be anything) that appear between two known substrings. For example, I have a string:

a<-" 任何东西都放在这里,STR1 GET_ME STR2,任何东西都放在这里"

我需要提取位于 STR1 和 STR2 之间的字符串 GET_ME(不含空格).

I need to extract the string GET_ME which is between STR1 and STR2 (without the white spaces).

我正在尝试 str_extract(a, "STR1 (.+) STR2"),但我得到了整个匹配

I am trying str_extract(a, "STR1 (.+) STR2"), but I am getting the entire match

[1] "STR1 GET_ME STR2"

我当然可以剥离已知的字符串,以隔离我需要的子字符串,但我认为应该有一种更简洁的方法来使用正确的正则表达式来做到这一点.

I can of course strip the known strings, to isolate the substring I need, but I think there should be a cleaner way to do it by using a correct regular expression.

推荐答案

您可以将 str_matchSTR1 (.*?) STR2 一起使用(注意空格是;有意义",如果您只想匹配 STR1STR2 之间的任何内容,请使用 STR1(.*?)STR2,或使用 STR1\\s*(.*?)\\s*STR2 修剪您需要的值).如果出现多次,请使用 str_match_all.

You may use str_match with STR1 (.*?) STR2 (note the spaces are "meaningful", if you want to just match anything in between STR1 and STR2 use STR1(.*?)STR2, or use STR1\\s*(.*?)\\s*STR2 to trim the value you need). If you have multiple occurrences, use str_match_all.

此外,如果您需要匹配跨越换行符/换行符的字符串,请在模式开头添加 (?s):(?s)STR1(.*?)STR2/(?s)STR1\\s*(.*?)\\s*STR2.

Also, if you need to match strings that span across line breaks/newlines add (?s) at the start of the pattern: (?s)STR1(.*?)STR2 / (?s)STR1\\s*(.*?)\\s*STR2.

library(stringr)
a <- " anything goes here, STR1 GET_ME STR2, anything goes here"
res <- str_match(a, "STR1\\s*(.*?)\\s*STR2")
res[,2]
[1] "GET_ME"

另一种使用基本 R regexec 的方法(获取第一个匹配项):

Another way using base R regexec (to get the first match):

test <- " anything goes here, STR1 GET_ME STR2, anything goes here STR1 GET_ME2 STR2"
pattern <- "STR1\\s*(.*?)\\s*STR2"
result <- regmatches(test, regexec(pattern, test))
result[[1]][2]
[1] "GET_ME"

这篇关于在R中的其他两个字符串之间提取一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆