ex02ChildrenInverse <- function(sentence) {
assertString(sentence)
matches <- regmatches(
sentence,
regexec('^(.*?) is the (father|mother) of "(.*?)"', sentence))[[1]]
parent <- matches[[2]]
male <- matches[[3]] == "father"
child <- matches[[4]]
child <- gsub('".*"', '', matches[4])
return(list(parent = parent, male = male, child = child))
}
字符串
这里是我的代码。我的问题是,我想输出孩子的名字,即使它有双引号在他的名字。F.e:
input: 'Gudrun is the mother of "Rosamunde ("Rosi")".'
型
我的输出:
$parent
\[1\] "Gudrun"
$male
\[1\] FALSE
$child
\[1\] "Rosamunde ("
but i want
$parent
\[1\] "Gudrun"
$male
\[1\] FALSE
$child
\[1\] "Rosamunde ("Rosi")"
型
我试过我的代码,它没有像我想的那样工作。
我想换child \<- gsub(.......)
2条答案
按热度按时间20jt8wwn1#
如果它总是字符串的最后一部分,你可以匹配最后一个双引号后面的点:
字符串
举例来说:
型
输出
型
参见R demo和regex demo
ma8fv8wu2#
一种新的代码方法是使用
gsub
和grepl
来获取你想要的相关信息,而不是尝试使用regmatches
来完成所有这些:字符串
或者稍微修改一下你现有的代码:
型
它将返回与上面相同的输出。