如何使 glob2rx 不添加“^"到正则表达式的开头? [英] How to make glob2rx not add "^" to beginning of regex?
问题描述
我正在使用 glob2rx 将用户输入转换为正则表达式以匹配文本模式.
I am using glob2rx to convert user input into regular expressions to match text patterns.
如果用户输入 run* ,我希望它匹配 runs 以及 running.
If the user inputs run* , I would like it to match runs as well as running.
glob2rx 在构造正则表达式方面效果很好,但它总是在正则表达式的开头添加一个 ^,即它只会匹配字符串开头的项目.但是,我也想匹配字符串中的标记.例如,在下面的例子中,它不匹配 I am running,只有 running am I 因为它返回正则表达式模式 ^run -我希望它创建run.
glob2rx works very well in constructing the regex, but it always adds a ^ to the beginning of the regex, i.e. it will match only items at the beginning of the string. However, I would like to match tokens within the string as well. For instance, in the example below, it does not match I am running, only running am I as it returns the regex pattern ^run - I would like it to create run.
regex = glob2rx("run*")
for (t in c("running am i", "i am running")) {
print (grep(regex, t))
}
有什么简单的方法可以使这项工作顺利进行吗?
Is there an easy way to make this work?
谢谢!
推荐答案
你可以用 gsub
去掉开头的 ^
:
You can strip off the initial ^
with gsub
:
gsub("^\\^", "", glob2rx("run*"))
但是 glob2rx
是为特定类型的输入(文件路径globs")设计的,因此可能会出现其他问题,因为该函数是为该输入设计的.
But glob2rx
is designed for a specific kind of input (file path "globs"), so there may be other issues that pop up because the function is designed for that input.
这篇关于如何使 glob2rx 不添加“^"到正则表达式的开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!