Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.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
使用POSIX字符类删除R中字符之间的所有标点符号(下划线除外)_R_Posix_Gsub - Fatal编程技术网

使用POSIX字符类删除R中字符之间的所有标点符号(下划线除外)

使用POSIX字符类删除R中字符之间的所有标点符号(下划线除外),r,posix,gsub,R,Posix,Gsub,我想用R删除所有的下划线,除了单词之间的下划线。在末尾,代码会删除单词末尾或开头的下划线。 结果应该是 “你好世界和你好世界”。 我想使用那些预构建的类。好的,我知道我已经学会在下面的代码中使用特定字符,但我不知道如何使用单词边界序列 test<-"hello_world and _hello_world_" gsub("[^_[:^punct:]]", "", test, perl=T) test一种非正则表达式的方法是通过将

我想用R删除所有的下划线,除了单词之间的下划线。在末尾,代码会删除单词末尾或开头的下划线。 结果应该是 “你好世界和你好世界”。 我想使用那些预构建的类。好的,我知道我已经学会在下面的代码中使用特定字符,但我不知道如何使用单词边界序列

test<-"hello_world and _hello_world_"
gsub("[^_[:^punct:]]", "", test, perl=T)

test一种非正则表达式的方法是通过将
whitespace
参数设置为
\uu
来拆分和使用
trimws
,即

paste(sapply(strsplit(test, ' '), function(i)trimws(i, whitespace = '_')), collapse = ' ')
#[1] "hello_world and hello_world"
您可以使用:

test <- "hello_world and _hello_world_"
output <- gsub("(?<![^\\W])_|_(?![^\\W])", "", test, perl=TRUE)
output

[1] "hello_world and hello_world"
测试
正则表达式的解释:

(?<![^\\W])  assert that what precedes is a non word character OR the start of the input
_            match an underscore to remove
|            OR
_            match an underscore to remove, followed by
(?![^\\W])   assert that what follows is a non word character OR the end of the input
(?您可以使用

gsub("[^_[:^punct:]]|_+\\b|\\b_+", "", test, perl=TRUE)

详情:

  • [^.[:^punct:]
    -除
    以外的任何标点符号
  • |
    -或
  • +\b
    -单词末尾的一个或多个
  • |
    -或
  • \b.+
    -一个单词开头的一个或多个

我们可以删除任何一端都有单词边界的所有底层。我们使用正向的lookahead和lookbehind正则表达式来查找这些底层。要在开始和结束时删除底层,我们使用
trimws

test<-"hello_world and _hello_world_"
gsub("(?<=\\b)_|_(?=\\b)", "", trimws(test, whitespace = '_'), perl = TRUE)
#[1] "hello_world and hello_world"

test注意
(?注意
(?与
(?![^\\W))相同
(?!\\W)
相同。使用
(?与
(?![^\\W])
只有在计划添加异常时才有效。此
[:punch:
非常巧妙:“否定版本,如
[:^alpha:]
使用
\P
而不是
\P
”()