下面是我的R对象(x)和一些有效的命令,有些则没有。
(x <- c("q10_1", "q10_2", "q10_11", "q12_1", "q12_2", "q13_1", "q13_11"))
# Which strings start with "q10" or "q12? - WORKS
x[grep("^q10|q12", x)]
# Which strings end with "1"? - WORKS
x[grep("1$", x)]
# Which strings end with "_1"? - WORKS
x[grep("\\_1$", x)]
# Which strings start with "q10" AND contain a "1"? - WORKS
x[grep("^q10.+1", x)]
# Which strings start with "q10" AND end with a "_1"? - DOES NOT WORK
x[grep("^q10.+\\_1$", x)]
# Which strings start with "q10" or "q12 AND end with "_1"? - WORKS INCORRECTLY
x[grep("^q10|q12.+\\_1$", x)]
谢谢!
答案 0 :(得分:2)
以下全部修复和优化:
x <- c("q10_1", "q10_2", "q10_11", "q12_1", "q12_2", "q13_1", "q13_11")
## Which strings start with "q10" or "q12? - WORKS - FIXED
x[grep("^q1[02]", x)]
## Which strings end with "1"? - WORKS
x[grep("1$", x)]
## Which strings end with "_1"? - WORKS - FIXED
x[grep("_1$", x)]
## Which strings start with "q10" AND contain a "1"? - WORKS - FIXED
x[grep("^q10.*1", x)]
## Which strings start with "q10" AND end with a "_1"? - DOES NOT WORK - FIXED
x[grep("^q10.*_1$", x)]
## Which strings start with "q10" or "q12 AND end with "_1"? - WORKS INCORRECTLY - FIXED
x[grep("^q1[02].*_1$", x)]
请参阅IDEONE demo
注意:
^q10|q12
可以表示为^q1[02]
,以提高效果并缩短模式。这也解决了^q10|q12
与q12
在输入内的任何位置匹配时遇到的问题。\\_1$
- 您无需逃避下划线^q10.+1
- 您需要使用*
量词,因为1
之后可能会q10
*
匹配0个或更多字符,+
至少需要1.因此,您没有匹配。^q10|q12.+\\_1$
- 在开始时匹配q10
,最后匹配q12.+_1
,由于缺少分组(^(q10|q12).+\\_1$
),逻辑被破坏了,但最好是使用^q1[02].*_1$
。