简体   繁体   English

Ruby正则表达式问题

[英]Ruby Regular Expression issue

Here is my program: 这是我的程序:

contact_data = [
  ["joe@email.com", "123 Main st.", "555-123-4567"],
  ["sally@email.com", "404 Not Found Dr.", "123-234-3454"]
]

("Joe Smith").downcase #=> "joe smith"
contact_data[0][0].slice(0..2) #=> "joe"

("Joe Smith").downcase =~ /contact_data[0][0].slice(0..2)/ #=> nil

Why does my regex not show a match? 为什么我的正则表达式不显示匹配项?

You cannot embed code inside a regular expression like that. 您不能像这样将代码嵌入正则表达式中。

If that worked, how could Ruby possibly know whether this regular expression... 如果这样可行,Ruby怎么可能知道这个正则表达式是否...

x = 3
/x/

... was supposed to match 3 or the literal character x ? ...应该匹配3或文字字符x How could you write a regular expression to match a simple character x if you had a variable x defined in the local scope? 你怎么写一个正则表达式匹配一个简单的字符x ,如果你有一个变量x在局部范围内定义的?

If you want to embed data inside a regular expression, you need to be much more explicit. 如果要将数据嵌入到正则表达式中,则需要更加明确。 Use #{} to interpolate the value as you would with a string: 使用#{}来插值,就像使用字符串一样:

/#{contact_data[0][0].slice(0..2)}/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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