2017-03-06 51 views
-2

我有一个类似的格式的字符串:如何从复杂字符串中删除引号?

A <- c("date: 27/08/2016","name: AAA","Question 4: yes") 

我想删除引号。

我已经试过

A1 <- noquote(A) 
class(A1) 
[1] "noquote" 

但是,这不会导致一个字符类,这是我需要什么。

我也试过

sub(" \" ", "", A) 
[1] "date: 27/08/2016" "name: AAA"  "Question 4: yes" 

但这并没有工作。欢迎任何建议。提前致谢。

我问的原因是我想使用函数sub来提取部分字符串。然而,这并不工作:

sub(".*date: *(.*?) *Question 4:.*", "\\1", A) 
[1] "date: 27/08/2016" "Question 4: yes 34" "name: AAA " 

虽然这个工程:

A1 <- "date: 27/08/2016 Question 4: yes 34 name: AAA" 
sub(".*date: *(.*?) *Question 4:.*", "\\1", A1) 
[1] "27/08/2016" 

因此,如何从A到A1?

谢谢!

+5

我觉得引号是不实际字符串的一部分...他们只是让你知道它是一个字符串... – ira

+0

...也许你正在想要尝试使用'cat()'在控制台上播放'A'? – joran

+0

如果'substr(A,1,1)'返回一个字母,那么引号不是字符串的一部分。 – manotheshark

回答

0

如果您在字符串内引用了字符串,则只需使用gsub替换引号即可。

例如目的产生的一些数据:

test_data <- sapply(c(1,0,0,1,1,1,0,1), function(i){ 
    if(i > 0){ 
    sprintf('%s and some quoted strings "%s"', 
     paste0(collapse = "",sample(letters[1:26],8)), 
     paste0(collapse = "",sample(letters[1:26],8))) 
    }else { 
     "" 
    } 
}) 

> cat(test_data,sep = "\n") 
gkseovij and some quoted strings "cvkpixdw" 


ljhnbyxg and some quoted strings "xqivclns" 
ybmvfasn and some quoted strings "hwiqvdtp" 
mfnhjdau and some quoted strings "fzjwnqom" 

upzockwx and some quoted strings "oxyfdqpe" 

现在SUB OUT:

> cat(gsub('\\"','',test_data),sep = "\n") 
gkseovij and some quoted strings cvkpixdw 


ljhnbyxg and some quoted strings xqivclns 
ybmvfasn and some quoted strings hwiqvdtp 
mfnhjdau and some quoted strings fzjwnqom 

upzockwx and some quoted strings oxyfdqpe 

编辑基于评论...

> paste0(A, collapse = " ") 
[1] "date: 27/08/2016 name: AAA Question 4: yes" 
+0

非常感谢,但我得到了一个奇怪的答案:><> cat(gsub(' \\“','',A),sep =”\ n“) date:27/08/2016 问题4:是34 name:AAA我真的需要将文本作为一行,以便我可以拿出我需要的元素 – ZMacarozzi

+0

@ZMacarozzi看到上面..你在说什么简单的粘贴? –

+0

是的!!非常感谢!哇,我不知道它是如此轻松 – ZMacarozzi