使用R如何根据字符分隔字符串

时间:2016-09-01 15:06:21

标签: r gsub regsub

我有一组字符串,我需要搜索中间有句号的单词。有些字符串是串联的,所以我需要将它们分成单词,以便我可以过滤带点的单词。

以下是我所拥有的以及到目前为止所获得的样本

 punctToRemove <- c("[^[:alnum:][:space:]._]")

 s <- c("get_degree('TITLE',PERS.ID)",
        "CLIENT_NEED.TYPE_CODe=21",
        "2.1.1Report Field Level Definition",
        "The user defined field. The user will validate")

这是我目前得到的

gsub(punctToRemove, " ", s)

[1] "get_degree  TITLE  PERS.ID "                   
[2] "CLIENT_NEED.TYPE_CODe 21"                      
[3] "2.1.1Report Field Level Definition"            
[4] "The user defined field. The user will validate"

我想要的样本在下面

[1] "get_degree ( ' TITLE ' , PERS.ID ) "          # spaces before and after the "(", "'", ",",and ")"
[2] "CLIENT_NEED.TYPE_CODe = 21"                   # spaces before and after the "=" sign. Dot and underscore remain untouched.        
[3] "2.1.1Report Field Level Definition"           # no changes 
[4] "The user defined field. The user will validate" # no changes

2 个答案:

答案 0 :(得分:2)

我们可以使用正则表达式外观

s1 <- gsub("(?<=['=(),])|(?=['(),=])", " ", s, perl = TRUE)
s1
#[1] "get_degree ( ' TITLE ' , PERS.ID ) "           
#[2] "CLIENT_NEED.TYPE_CODe = 21"                    
#[3] "2.1.1Report Field Level Definition"            
#[4] "The user defined field. The user will validate"

nchar(s1)
#[1] 35 26 34 46

等于OP预期输出中显示的字符数。

答案 1 :(得分:0)

对于这个例子:

   library(stringr)
    s <- str_replace_all(s, "\\)", " \\) ")
    s <- str_replace_all(s, "\\(", " \\( ")
    s <- str_replace_all(s, "=", " = ")
    s <- str_replace_all(s, "'", " ' ")
    s <- str_replace_all(s, ",", " , ")