Way to partially match a Ruby string using Regexp
I'm working on 2 cases:
assume I have those var:
a = "hello"
b = "hello-SP"
c 开发者_C百科= "not_hello"
Any partial matches
I want to accept any string that has the variablea
inside, sob
andc
would match.Patterned match
I want to match a string that hasa
inside, followed by'-'
, sob
would match,c
does not.
I am having problem, because I always used the syntax /expression/
to define Regexp, so how dynamically define an RegExp on Ruby?
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
reg2 = /#{a}-/
would do the same, plus a hyphen, so hello-
in your example.
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. 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:
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"
精彩评论