我想在R中编写正则表达式来验证用户输入并相应地运行程序。 预计有3种类型的查询,都是字符向量。在R中验证输入字符串的正则表达式
query1 = "Oct4[Title/Abstract] AND BCR-ABL1[Title/Abstract]
AND stem cells[Title] AND (2000[PDAT] :2015[PDAT])"
query2 <-c("26527521","26711930","26314551")
以下代码有效。但面临的挑战是在两种情况下
all(grepl("[A-Za-z]+",query,perl=TRUE)) validates False for query 2
或@sebkopf建议限制特殊字符
all(grepl("^[0-9 ,]+$", query)) # evaluates to TRUE only for query 2
然而,查询1也需要在一年的输入,这意味着它的数字输入应该被接受查询1.为了增加复杂性,在query1中允许使用space , . - []()
。而且,查询2的格式应该只是数字,用, or space
分隔。其他任何事情都应该抛出一个错误。
如何将这两个条件合并为R正则表达式的一部分?那么,下面的if conditions
被验证相应地运行相应的代码?
if (grepl("regex for query 1& 2",query,perl=TRUE) == True {
Run code 1
} else { print ("these characters are not allowed @ ! & % # * ~ `_ = +") }
if (grepl("regex for query3",query,perl=TRUE) == True {
Run code 2
} else { print ("these characters are not allowed @ ! & % # * ~ `_ = + []() - . ")}
什么是你的问题? – simbabque
对不起,监督。寻找解决方案,将允许一些特殊字符和限制其他? – user5249203
然后请删除多余的内容,只保留与问题相关的内容。而[MVCE(最小完整的可验证示例)](http://stackoverflow.com/help/mcve)会很有帮助。 –