Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中的正则表达式中指定一个单词后跟一个特定单词,后跟最多3个单词_R_Regex_String - Fatal编程技术网

在R中的正则表达式中指定一个单词后跟一个特定单词,后跟最多3个单词

在R中的正则表达式中指定一个单词后跟一个特定单词,后跟最多3个单词,r,regex,string,R,Regex,String,我正在寻找一种我似乎无法获得的特定正则表达式模式: 神秘地说: pattern <- "[1 word|no word][this is][1-3 words max]" text <- c("this guy cannot get a mortgage, this is a fake application", "this is a new application", "hi this is a specifi

我正在寻找一种我似乎无法获得的特定正则表达式模式:

神秘地说:

pattern <- "[1 word|no word][this is][1-3 words max]"

text <- c("this guy cannot get a mortgage, this is a fake application", "this is a new application", "hi this is a specific question", "this is real", "this is not what you are looking for")

str_match("pattern", text)
这应该是可行的,但我正在努力的文字和最大数量的它在正则表达式 有人能帮我做这个吗?

grepl(“^(\\S+\\S*)?这是\\S*\\S*\\S*\\S*\\S*\\S*\\S*$”,text,perl=TRUE)
#[1]假-真-假
这似乎有点野蛮,但它允许

  • ^(\\S+\\S*)?
    前面的零个或一个单词
  • 文本
    这是
    (后跟零个或多个空格),然后
  • 至少,
    \\S+
    一个单词(至少有一个字母),然后
  • 可能是空格和一个单词
    \\s*\\s*
    ,两次,最多允许三个单词
根据您打算如何使用此选项,您可以使用
strcapture
(仍以R为基数)将单词提取到单列或多列中:

strcapture(“^(\\S+\\S*)?这是\\S*(\\S+\\S*\\S*\\S*\\S*)$”,文本,
proto=list(ign=“”,w1=“”),perl=TRUE)[,-1,drop=FALSE]
#w1
# 1                
#2新的应用程序
#3具体问题
#4真实的
# 5                
strcapture(“^(\\S+\\S*)?这是\\S*(\\S+)\\S*(\\S*)\\S*(\\S*)\\S*(\\S*)$”,文本,
proto=list(ign=“”,w1=“”,w2=“”,w3=“”),perl=TRUE)[,-1,drop=FALSE]
#w1 w2 w3
# 1              
#2新的应用程序
#3具体问题
#4真实的
# 5              
[,-1,drop=FALSE]
是因为我们需要
(…)
捕获
“这是”
之前的单词,这样它就可以是可选的,但我们不需要保留它们,所以我会立即删除它们。(drop=FALSE是因为base R
data.frame
默认将单列返回减少为向量。)


轻微改进(减少暴力),允许通过编程确定要接受的字数


text2如果您询问关于R的信息,为什么要添加python标记?DataCastle,StackExchange标记推荐系统是可以的,但它偶尔会提供不好的建议。在这种情况下,您允许它提出建议,但问题中不建议/支持该建议。请更加了解正在使用的标签;“更多”可以获得更多的关注,因此获得答案的可能性也更大,但不相关的标签可能会招致否决票、接近票和/或只是负面反应。此外,虽然熟悉R软件包生态系统的人可能很容易推断您正在使用
stringr
软件包,你相信那是不明智的。请明确使用非基本R包。如果您还没有访问过这些问题,那么可以在以下几个地方阅读有关如何设置可复制和自包含问题的格式的内容:参考文献:,和。谢谢谢谢你的快速回复,它解决了我的问题,尽管它看起来确实有点暴力!DataCastle,请参见我的编辑,略有改进。
[1]FALSE  #cause too many words in front
[2]TRUE   
[3]TRUE
[4]TRUE
[5]FALSE  #cause too many words behind it