tags:

views:

122

answers:

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?

+6  A: 

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
Yar
Another option would be to use Regexp.new, i.e. `reg2 = Regexp.new("#{a}-")`.
Greg Campbell
@Greg Campbell, yes, but that's more letters :)
Yar
If `a` might have any regexp metacharacters (period, star, etc.), then wrap it in a call to `Regexp.escape`.
Wayne Conrad
@Wayne Conrad, adusted my answer, does that work for you?
Yar
Heck, yeah. Good answer, even before the edit.
Wayne Conrad
Cool thanks @Wayne Conrad
Yar