使用通配符匹配区间
Match on interval with wildcard
我有两个值,例如:
from = XY05*
to = XY55*
然后我有一个包含很多字符串的tbl_dff
。
Codes = ["XY05A", "XY56", "XY555", "AT003", "XY55AB", "XY35QA"
"GA003A", "XY36", "XY100", "XY03",...]
我想使用我的变量 from
和 to
来查看这些变量是否在我的 Codes
变量中。
根据示例,我希望匹配:
"XY05A"
"XY555"
"XY36"
"XY55AB"
"XY35QA"
因为在XY05* - XY55*
之间。 *
只是说,我不在乎后面是什么。
希望这是有道理的。
试试这个模式:XY(0[5-9]|[1-4]\d|5[0-5]).*
。
(0[5-9]|[1-4]\d|5[0-5])
将匹配 05
和 55
之间的任意数字以及之后的任意数量的任意字符。
你能把 from
和 to
作为整数而不是完整的字符串吗?这样你就可以从 Codes
向量中提取整数,并将它们直接与 from
和 to
:
进行比较
from <- 5
to <- 55
pattern <- "XY([0-9]+).*"
# use regex to extract the integer part of each string
Codes_int <- as.integer( sub( pattern, "\1", Codes ) )
# return only the `Codes` where the integer is in range
Codes[ Codes_int >= from & Codes_int <= to & grepl( pattern, Codes ) ]
我有两个值,例如:
from = XY05*
to = XY55*
然后我有一个包含很多字符串的tbl_dff
。
Codes = ["XY05A", "XY56", "XY555", "AT003", "XY55AB", "XY35QA"
"GA003A", "XY36", "XY100", "XY03",...]
我想使用我的变量 from
和 to
来查看这些变量是否在我的 Codes
变量中。
根据示例,我希望匹配:
"XY05A"
"XY555"
"XY36"
"XY55AB"
"XY35QA"
因为在XY05* - XY55*
之间。 *
只是说,我不在乎后面是什么。
希望这是有道理的。
试试这个模式:XY(0[5-9]|[1-4]\d|5[0-5]).*
。
(0[5-9]|[1-4]\d|5[0-5])
将匹配 05
和 55
之间的任意数字以及之后的任意数量的任意字符。
你能把 from
和 to
作为整数而不是完整的字符串吗?这样你就可以从 Codes
向量中提取整数,并将它们直接与 from
和 to
:
from <- 5
to <- 55
pattern <- "XY([0-9]+).*"
# use regex to extract the integer part of each string
Codes_int <- as.integer( sub( pattern, "\1", Codes ) )
# return only the `Codes` where the integer is in range
Codes[ Codes_int >= from & Codes_int <= to & grepl( pattern, Codes ) ]