使用通配符匹配间隔

问题描述 投票:1回答:2

我有两个值,例如:

from = XY05*
to = XY55*

然后我有一个包含很多字符串的tbl_dff

Codes = ["XY05A", "XY56", "XY555", "AT003", "XY55AB", "XY35QA"
              "GA003A", "XY36", "XY100", "XY03",...]

我想使用我的变量fromto来查看这些是否在我的Codes变量中。

从示例中,我希望有一个匹配:

"XY05A"
"XY555"
"XY36"
"XY55AB"
"XY35QA"

因为它介于XY05* - XY55*之间。 *只是说,我不在乎后者是什么。

希望这是有道理的。

r regex pattern-matching matching
2个回答
1
投票

尝试这种模式:XY(0[5-9]|[1-4]\d|5[0-5]).*

(0[5-9]|[1-4]\d|5[0-5])将匹配0555之间的任何数字以及之后任意数量的任何字符。

Demo


0
投票

你能用fromto作为整数而不是完整的字符串吗?这样你就可以从Codes向量中提取整数,并将它们直接与fromto进行比较:

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 ) ]
© www.soinside.com 2019 - 2024. All rights reserved.