How do I use variables with regular expressions?
Originally from this thread.
In order to use regular expressions with variables, you need to build your string using the Regexp.new( 'pattern' [, options]) syntax.
# a is a string
irb(main):001:0> a = "foofar"
=> "foofar"
# create a new regular expression, b, from the string in a
# this is the same as writing b = Regexp.new "foofar"
irb(main):002:0> b = Regexp.new a
=> /foofar/
# obtain the string between the / characters
irb(main):003:0> b.source
=> "foofar"
# the regular expression itself
irb(main):004:0> b
=> /foofar/
# a string representation of the regexp as you would expect to see it in code
irb(main):005:0> b.inspect
=> "/foofar/"
# a different string representation of the regexp
irb(main):006:0> b.to_s
=> "(?-mix:foofar)"
# additional examples
irb(main):001:0> var = 'today'
=> "today"
irb(main):002:0> my_string = 'here today gone tomorrow'
=> "here today gone tomorrow"
irb(main):003:0> b = Regexp.new var
=> /today/
# note that a regular expression match returns nil if not found
# and a number if successful indicating the position in the string
# where the match was found
irb(main):004:0> my_string =~ b
=> 5
irb(main):005:0> var1 = 'tom'
=> "tom"
irb(main):006:0> c = Regexp.new var1 + 'orrow'
=> /tomorrow/
irb(main):007:0> my_string =~ c
=> 16
No comments:
Post a Comment