Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.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中特定单词开头的完整句子_R_Regex - Fatal编程技术网

需要提取以R中特定单词开头的完整句子

需要提取以R中特定单词开头的完整句子,r,regex,R,Regex,我需要提取以R中特定单词开头的完整句子。下面是我试图使用的代码,但无法获得所需的结果。我不熟悉R中的正则表达式概念。我想提取以单词“database”开头的句子 sent <- c("database connection","connection database fail", "fail connection database","database connection is good") m <- gregexpr('database.*', sent) regmatch

我需要提取以R中特定单词开头的完整句子。下面是我试图使用的代码,但无法获得所需的结果。我不熟悉R中的正则表达式概念。我想提取以单词“database”开头的句子

 sent <- c("database connection","connection database fail", "fail connection database","database connection is good")
 m <- gregexpr('database.*', sent)
 regmatches(sent, m)

谢谢你的帮助

您没有将正则表达式锚定到行的前端。如果使用前锚点(
^
),将获得所需的结果。以下是您的代码的外观:

sent <- c("database connection","connection database fail", "fail connection database","database connection is good")
m <- gregexpr('^database.*', sent)
regmatches(sent, m)

您没有将正则表达式锚定到行的前端。如果使用前锚点(
^
),将获得所需的结果。以下是您的代码的外观:

sent <- c("database connection","connection database fail", "fail connection database","database connection is good")
m <- gregexpr('^database.*', sent)
regmatches(sent, m)

stringr

sent[1]“数据库连接”“数据库连接良好”

以R为基数:

sent[1]“数据库连接”“数据库连接良好”

stringr

sent[1]“数据库连接”“数据库连接良好”

以R为基数:

sent[1]“数据库连接”“数据库连接良好”

Try
m抱歉,它没有给出期望的结果。也许,Try
m抱歉,它没有给出期望的结果。也许,谢谢Eli Sadoff,我理解我的错误。它起作用了。有一件事,我怎样才能去掉[[2]]和[[3]]上面写着“字符(0)”,只打印匹配的句子呢?我在答案中添加了这一点。太好了……非常感谢。这对我有用。我在过去一个小时里一直在挣扎。仅供参考,当字符串开头有
数据库时,此
'^database.*'
regex也会找到匹配项。或
数据库0001
。要将其作为一个整体匹配(如果需要),请在单词后使用
\\b
,并且
*
是多余的。@WiktorStribiżew这是正确的,但是对于用例,更简单的正则表达式似乎很好。感谢Eli Sadoff,我理解了我的错误。它起作用了。有一件事,我怎样才能去掉[[2]]和[[3]]上面写着“字符(0)”,只打印匹配的句子呢?我在答案中添加了这一点。太好了……非常感谢。这对我有用。我在过去一个小时里一直在挣扎。仅供参考,当字符串开头有
数据库时,此
'^database.*'
regex也会找到匹配项。或
数据库0001
。要将其作为一个整体匹配(如果需要),请在单词后使用
\\b
,并且
*
是多余的。@WiktorStribiżew这是正确的,但是对于这个用例,更简单的正则表达式似乎很好。感谢Titolodon的指导。这对我有用。@Kiwi。很高兴我能帮助你。别忘了通过验证你的答案来结束问题。谢谢蒂托洛顿的指导。这对我有用。@Kiwi。很高兴我能帮助你。别忘了通过验证你的答案来结束提问。
r <- regmatches(sent, m)
r <- r[lapply(r,length)>0]