开发者

Way to partially match a Ruby string using Regexp

开发者 https://www.devze.com 2022-12-28 06:50 出处:网络
I\'m working on 2 cases: assume I have those var: a = \"hello\" b = \"hello-SP\" c 开发者_C百科= \"not_hello\"

I'm working on 2 cases:

assume I have those var:

a = "hello"
b = "hello-SP"
c 开发者_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" 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号