不区分大小写,检查两个字符串是否匹配

时间:2021-07-23 20:10:55

I am trying to do a full text match on a string. Something like this:

我正在尝试对字符串进行全文匹配。像这样的东西:

If a user types in "beastie boys", I need to see if it matches the Capitalized/camel case (Beastie Boys) equivalent.

如果用户键入“beastie boys”,我需要查看它是否与大写/骆驼案(Beastie Boys)相当。

I have tried this:

我试过这个:

str = "beastie boys"
str2 = "Beastie Boys"

puts str2.match(str)

Every time it comes back as nil.

每当它回来时为零。

3 个解决方案

#1


3  

Use casecmp:

str2.casecmp(str) == 0

#2


0  

Try this:

str = "Beasty Boys"
str.match /beasty\sboys/i

#3


0  

Coming back as nil is the same as false. When it matches it returns a MatchData object containing your string.

返回nil与false相同。匹配时返回包含字符串的MatchData对象。

so you could do

所以你可以做到

if (str2.match(str))
  #do stuff
end

if you want to ignore case and match regardless

如果你想忽略大小写和匹配

if (str2.downcase.match(str))
  #do stuff
end

and it will work

它会起作用

#1


3  

Use casecmp:

str2.casecmp(str) == 0

#2


0  

Try this:

str = "Beasty Boys"
str.match /beasty\sboys/i

#3


0  

Coming back as nil is the same as false. When it matches it returns a MatchData object containing your string.

返回nil与false相同。匹配时返回包含字符串的MatchData对象。

so you could do

所以你可以做到

if (str2.match(str))
  #do stuff
end

if you want to ignore case and match regardless

如果你想忽略大小写和匹配

if (str2.downcase.match(str))
  #do stuff
end

and it will work

它会起作用