1

I'm working on 2 cases:

assume I have those var:

a = "hello"
b = "hello-SP"
c = "not_hello"
  1. Any partial matches
    I want to accept any string that has the variable a inside, so b and c would match.

  2. Patterned match
    I want to match a string that has a inside, followed by '-', so b 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?

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Another option would be to use Regexp.new, i.e. reg2 = Regexp.new("#{a}-").
@Greg Campbell, yes, but that's more letters :)
If a might have any regexp metacharacters (period, star, etc.), then wrap it in a call to Regexp.escape.
0

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" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.