【问题标题】:R regex to validate user input is correctR 正则表达式验证用户输入是否正确
【发布时间】:2011-01-27 22:16:44
【问题描述】:

我正在尝试编写更好的代码,所以我想用正则表达式验证我的输入序列,以确保我得到的第一件事是一个字母 A 到 H,第二个是数字 1 到 12只要。我是正则表达式的新手,不确定表达式应该是什么样子。我也不确定如果这无效,R 会抛出什么类型的错误?

我认为在 Perl 中应该是这样的:=~ m/([A-M]?))/)

这是我目前对 R 的了解:

input_string = "A1"
first_well_row = unlist(strsplit(input_string, ""))[1]  # get the letter out
first_well_col = unlist(strsplit(input_string, ""))[2]  # get the number out  

【问题讨论】:

    标签: regex r


    【解决方案1】:

    在 R 代码中,使用 David 的正则表达式:[编辑以反映 Marek 的建议]

    validate.input <- function(x){
      match <- grepl("^[A-Ha-h]([0-9]|(1[0-2]))$",x,perl=TRUE)
      ## as Marek points out, instead of testing the length of the vector
      ## returned by grep() (which will return the index of the match and integer(0) 
      ## if there are no matches), we can use grepl()
      if(!match) stop("invalid input")
      list(well_row=substr(x,1,1), well_col=as.integer(substr(x,2,nchar(x))))
    }
    

    这只会产生错误。如果您想更好地控制错误处理,请查看 tryCatch 的文档,这是一个原始用法示例(而不是像之前我们将返回 NA 那样得到错误):

    validate.and.catch.error <- function(x){
      tryCatch(validate.input(x), error=function(e) NA)
    }
    

    最后请注意,您可以使用substr 来提取字母和数字,而不是进行strsplit。

    【讨论】:

    • 为了使第一行更短更容易理解,请参阅stringr 包中的str_detect
    • 感谢您更新。从来没有编程过 R,我在那里不知所措。我认为它具有 Perl 类型的正则表达式语法?
    • 是的,它执行基本、扩展(默认)和 PCRE(使用 perl=TRUE 标志)表达式。 @hadley:stringr 看起来很方便!
    • 可以用grepl()代替length(grep())&gt;0
    【解决方案2】:

    您专门要求“A 到 H,然后是 0-9 或 10-12”。调用异常“InvalidInputException”或任何类似名称的对象-“Not Valid”“Input”“Exception”

    /^[A-H]([0-9]|(1[0-2]))$/
    

    在伪代码中:

    validateData(String data)
      if not data.match("/^[A-H]([0-9]|(1[0-2]))$/")
        throw InvalidInputException
    

    【讨论】:

      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多