如何比较忽略大小写的字符串

时间:2010-05-16 16:28:45

标签: ruby string string-comparison

我希望appleApple比较为true。 目前

"Apple" == "Apple"  # returns TRUE
"Apple" == "APPLE"  # returns FALSE

5 个答案:

答案 0 :(得分:257)

您正在寻找casecmp。如果两个字符串相等,则返回0,不区分大小写。

str1.casecmp(str2) == 0

"Apple".casecmp("APPLE") == 0
#=> true

或者,您可以将两个字符串转换为小写字母(str.downcase)并比较相等。

答案 1 :(得分:35)

Ruby 2.4.0 中,您有:<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <manifestEntries> <Main-Class>com.example.Server</Main-Class> </manifestEntries> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>META-INF/services/io.vertx.core.spi.VerticleFactory</resource> </transformer> </transformers> <artifactSet> </artifactSet> <outputFile>${project.build.directory}/${project.artifactId}-${project.version}-fat.jar </outputFile> <filters> <filter> <!-- Fix java.lang.SecurityException: Invalid signature file digest for Manifest main attributes when server starts inside Docker container due to inclusion of OpenSAML and use of uber-jar / maven-shade-plugin. See http://stackoverflow.com/a/6743609 --> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> <filter> <!-- This was one of my attempts to fix the problem. Unfortunately, it doesn't work. --> <artifact>org.opensaml:opensaml-saml-impl</artifact> <includes> <include>**</include> </includes> </filter> </filters> </configuration> </execution> </executions> </plugin>

casecmp?(other_str) → true, false, or nil

Here you have more info

答案 2 :(得分:8)

如果你必须比较忽略大小写的UTF-8字符串:

>> str1 = "Мария"
=> "Мария"
>> str2 = "мария"
=> "мария"
>> str1.casecmp(str2) == 0
=> false
>> require 'active_support/all'
=> true
>> str1.mb_chars.downcase.to_s.casecmp(str2.mb_chars.downcase.to_s) == 0
=> true

它在Ruby 2.3.1及更早版本中以这种方式工作。

对于较小的内存占用,您可以选择string/multibyte

require 'active_support'
require 'active_support/core_ext/string/multibyte'

编辑,Ruby 2.4.0:

>> str1.casecmp(str2) == 0
=> false

所以casecmp在2.4.0中不起作用;但是在2.4.0中,可以在没有active_support gem的情况下手动比较UTF-8字符串:

>> str1.downcase == str2.downcase
=> true

答案 3 :(得分:5)

casecmp和零?是红宝石内置的方法。如果两个字符串相等,casecmp返回0,不区分大小写并且为零?检查零值(== 0)

str1.casecmp(str2).zero?

答案 4 :(得分:0)

对于ruby 2.4,对于utf-8字符串,casecmp?可以正常工作(不需要mb_chars):

2.4.1 :062 > 'строка1'.casecmp?('СтроКа1')
 => true

但是casecmp无法用于utf-8:

2.4.1 :062 > 'строка1'.casecmp('СтроКА1')
 => 1
2.4.1 :063 > 'string1'.casecmp('StrInG1')
 => 0