【问题标题】:R - Detect any punctuation in value except for period [duplicate]R - 检测除句点以外的任何标点符号[重复]
【发布时间】:2020-06-16 03:31:05
【问题描述】:

我想检查除句点. 之外的任何标点符号的列或值。我查看了一堆类似的问题,但似乎无法正确解决。

期望的输出:

"1.0" FALSE
"-1.0" TRUE
"-1" TRUE
"1+" TRUE

尝试:

> grepl("([.])[[:punct:]]", "1.0")
[1] FALSE
> grepl("([.])[[:punct:]]", "-1.0")
[1] FALSE
> grepl("(.)[[:punct:]]", "-1.0")
[1] TRUE
> grepl("(.)[[:punct:]]", "1.0")
[1] TRUE

基于 R 是首选但也是必需的。

【问题讨论】:

  • 可能删除句点,然后将grepl[[:punct:]] 一起使用,例如grepl("[[:punct:]]", gsub("\\.", "", x))
  • @GregorThomas 很简单,它可以工作。在大型列上也应该足够快
  • 如果你想加快速度,在gsub中使用fixed = TRUE(见答案)。使用stringi 包可以让你更快一点。

标签: r regex


【解决方案1】:

您可以使用(?![.])[[:punct:]](?!\\.)[[:punct:]].[:punct:] 中排除负前瞻

x <- c("1.0", "-1.0", "-1", "1+")
grepl("(?![.])[[:punct:]]", x, perl=TRUE)
#[1] FALSE  TRUE  TRUE  TRUE

或使用双重否定,如@A5C1D2H2I1M1N2O1R2T1 在 cmets 中给出的那样。

grepl("[^[:^punct:].]", x, perl=TRUE)
#[1] FALSE  TRUE  TRUE  TRUE

但明确并用于您给定的示例 [-+][^[:digit:].][^0-9.] 可能会更好,

grepl("[-+]", x)
#[1] FALSE  TRUE  TRUE  TRUE

grepl("[^[:digit:].]", x)
#[1] FALSE  TRUE  TRUE  TRUE

grepl("[^0-9.]", x)
#[1] FALSE  TRUE  TRUE  TRUE

因为 如果一个区域设置生效,它可能会改变 [[:punct:]] 的行为,并在 perl=FALSEperl=TRUE 之间进行更改。

gsub("[^[:punct:]]", "", intToUtf8(c(32:126, 160:255)), perl=FALSE)
#[1] "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ¡¢£¤¥¦§¨©«¬­®¯°±²³´¶·¸¹»¼½¾¿×÷"

gsub("[^[:punct:]]", "", intToUtf8(c(32:126, 160:255)), perl=TRUE)
#[1] "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

另请参阅: in R, use gsub to remove all punctuation except period, R regex remove all punctuation except apostropheRemove all punctuation except apostrophes in R.

【讨论】:

    【解决方案2】:

    将其分为两步。首先删除句点,然后检测(剩余)标点符号:

    grepl("[[:punct:]]", gsub("\\.", "", x))
    
    ## use fixed = TRUE for a bit more speed in the gsub
    grepl("[[:punct:]]", gsub(".", "", x, fixed = TRUE))
    

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多