[英]Way to partially match a Ruby string using Regexp
I'm working on 2 cases: 我正在处理2种情况:
assume I have those var: 假设我有那些变量:
a = "hello"
b = "hello-SP"
c = "not_hello"
Any partial matches 任何部分匹配
I want to accept any string that has the variable a
inside, so b
and c
would match. 我想接受包含变量a
在内的任何字符串,因此b
和c
将匹配。
Patterned match 图案匹配
I want to match a string that has a
inside, followed by '-'
, so b
would match, c
does not. 我想匹配了字符串a
内部的,其次是'-'
,那么b
将会匹配, c
没有。
I am having problem, because I always used the syntax /expression/
to define Regexp, so how dynamically define an RegExp on Ruby? 我遇到了问题,因为我总是使用语法/expression/
来定义Regexp,那么如何在Ruby上动态定义RegExp?
You can use the same syntax to use variables in a regex, so: 您可以使用相同的语法在正则表达式中使用变量,因此:
reg1 = /#{a}/
would match on anything that contains the value of the a
variable (at the time the expression is created!) and 将匹配任何包含的值a
变量(在创建表达式的时候了!)和
reg2 = /#{a}-/
would do the same, plus a hyphen, so hello-
in your example. 会做同样的事情,加上连字符,所以在您的示例中, hello-
。
Edit: As Wayne Conrad points out, if a
contains "any characters that would have special meaning in a regular expression," you need to escape them. 编辑:正如Wayne Conrad所指出的那样,如果a
包含“任何在正则表达式中具有特殊含义的字符”,则需要转义它们。 Example: 例:
a = ".com"
b = Regexp.new(Regexp.escape(a))
"blah.com" =~ b
Late to comment but I wasn't able to find what I was looking for.The above mentioned answers didn't help me.Hope it help someone new to ruby who just wants a quick fix. 评论迟到了,但我找不到我想要的东西,上面提到的答案对我没有帮助,希望它能帮助刚接触红宝石的人快速解决问题。
Ruby Code: Ruby代码:
st = "BJ's Restaurant & Brewery"
#take the string you want to match into a variable
m = (/BJ\'s/i).match(string) #(/"your regular expression"/.match(string))
# m has the match #<MatchData "BJ's">
m.to_s
# this will display the match
=> "BJ's"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.