我正在尝试检查字符串是否遵循特定的模式。字符串必须遵循模式[check(id(“ numeric only”),“指定关键字的1”)],其中指定关键字= D,D5,W1,W2,W3,W4,W5,W6,W0,M ,Q1,Q2,Q3,H1,H2,H3,H4,H5,H6,Y1,Y2,A2,Y4,Y5,A3,Y7,Y8,A4,YA,YB,A1。
freq <- c("D", "D5", "W1", "W2", "W3", "W4", "W5", "W6", "W0", "M", "Q1",
"Q2", "Q3", "H1", "H2", "H3", "H4", "H5", "H6", "Y1", "Y2", "A2",
"Y4", "Y5", "A3", "Y7", "Y8", "A4", "YA", "YB", "A1")
> grepl("\\<check\\(id\\(+\\d+\\),\\bA1\\b|\\bA2\\b\\)\\>", "check(id(32131241w),A1)")
[1] FALSE
> grepl("\\<check\\(id\\(+\\d+\\),\\bA1\\b|\\bA2\\b\\)\\>", "check(id(32131241),A1)")
[1] TRUE
> grepl("\\<check\\(id\\(+\\d+\\),\\b", paste0(freq, collapse = "\\b|\\b"), "\\b\\)\\>", "check(id(32131241w),A1)")
[1] FALSE
> grepl("\\<check\\(id\\(+\\d+\\),\\b", paste0(freq, collapse = "\\b|\\b"), "\\b\\)\\>", "check(id(32131241),A1)")
[1] FALSE
第一个,第二个和第三个输出是正确的结果,但是我期望第四个结果是TRUE,但是R返回FALSE。
答案 0 :(得分:0)
#Second line from you
grepl("\\<check\\(id\\(+\\d+\\),\\bA1\\b|\\bA2\\b\\)\\>", "check(id(32131241),A1)")
#TRUE
#Change A1 to A2
grepl("\\<check\\(id\\(+\\d+\\),\\bA1\\b|\\bA2\\b\\)\\>", "check(id(32131241),A2)")
#FALSE
#Adding surrounding <>
grepl("\\<check\\(id\\(+\\d+\\),\\bA1\\b|\\bA2\\b\\)\\>", "<check(id(32131241),A2)>")
#FALSE
#Adding perl=TRUE
grepl("\\<check\\(id\\(+\\d+\\),\\bA1\\b|\\bA2\\b\\)\\>", "<check(id(32131241),A2)>", perl=TRUE)
#TRUE
#Add () arround |
grepl("\\<check\\(id\\(+\\d+\\),(\\bA1\\b|\\bA2\\b)\\)\\>", "<check(id(32131241),A2)>", perl=TRUE)
#TRUE
#Here you have to add one additional paste
grepl(paste0("\\<check\\(id\\(+\\d+\\),(\\b", paste0(freq, collapse = "\\b|\\b"), "\\b)\\)\\>"), "<check(id(32131241),A1)>", perl=TRUE)
#TRUE