简体   繁体   中英

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 = "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?

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM