ruby 如何在Ruby中检查字符串是否包含子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8258517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:31:54  来源:igfitidea点击:

How to check whether a string contains a substring in Ruby

rubystring

提问by BSalunke

I have a string variable with content:

我有一个包含内容的字符串变量:

varMessage =   
            "hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"


            "/my/name/is/balaji.so\n"
            "call::myFunction(int const&)\n"
            "void::secondFunction(char const&)\n"
             .
             .
             .
            "this/is/last/line/liobrary.so"

In the string I have to find a sub-string:

在字符串中,我必须找到一个子字符串:

"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"

"/my/name/is/balaji.so\n"
"call::myFunction(int const&)\n"

How can I find it? I need to determine whether the sub-string is present or not.

我怎样才能找到它?我需要确定子字符串是否存在。

回答by Adam Lear

You can use the include?method:

您可以使用以下include?方法:

my_string = "abcdefg"
if my_string.include? "cde"
   puts "String includes 'cde'"
end

回答by Clint Pachl

If case is irrelevant, then a case-insensitive regular expressionis a good solution:

如果大小写无关,那么不区分大小写的正则表达式是一个很好的解决方案:

'aBcDe' =~ /bcd/i  # evaluates as true

This will also work for multi-line strings.

这也适用于多行字符串。

See Ruby's Regexpclass for more information.

有关更多信息,请参阅 Ruby 的Regexp类。

回答by Oto Brglez

You can also do this...

你也可以这样做...

my_string = "Hello world"

if my_string["Hello"]
  puts 'It has "Hello"'
else
  puts 'No "Hello" found'
end

# => 'It has "Hello"'

This example uses Ruby's String #[]method.

此示例使用 Ruby 的 String#[]方法。

回答by acib708

Expanding on Clint Pachl's answer:

扩展 Clint Pachl 的回答:

Regex matching in Ruby returns nilwhen the expression doesn't match. When it does, it returns the index of the character where the match happens. For example:

nil当表达式不匹配时,Ruby 中的正则表达式匹配返回。当它发生时,它返回匹配发生的字符的索引。例如:

"foobar" =~ /bar/  # returns 3
"foobar" =~ /foo/  # returns 0
"foobar" =~ /zzz/  # returns nil

It's important to note that in Ruby only niland the boolean expression falseevaluate to false. Everything else, including an empty Array, empty Hash, or the Integer 0, evaluates to true.

需要注意的是,仅在 Ruby 中nil,布尔表达式的false计算结果为 false。其他所有内容,包括空数组、空哈希或整数 0,评估结果为真。

That's why the /foo/example above works, and why.

这就是为什么/foo/上面的例子有效,以及为什么。

if "string" =~ /regex/

works as expected, only entering the 'true' part of the ifblock if a match occurred.

按预期工作,只有在if匹配发生时才输入块的“真实”部分。

回答by stwr667

A more succinct idiom than the accepted answer above that's available in Rails (from 3.1.0 and above) is .in?:

比 Rails(从 3.1.0 及更高版本)中可用的上述公认答案更简洁的习语是.in?

my_string = "abcdefg"
if "cde".in? my_string
  puts "'cde' is in the String."
  puts "i.e. String includes 'cde'"
end

I also think it's more readable.

我也认为它更具可读性。

See the in?documentation for more information.

有关in?更多信息,请参阅文档。

Note again that it's only available in Rails, and not pure Ruby.

再次注意,它仅在Rails 中可用,而不是纯 Ruby。

回答by Mauro

Ternary way

三元方式

my_string.include?('ahr') ? (puts 'String includes ahr') : (puts 'String does not include ahr')

OR

或者

puts (my_string.include?('ahr') ? 'String includes ahr' : 'String not includes ahr')

回答by dawg

You can use the String Element Referencemethod which is []

您可以使用字符串元素引用方法,它是[]

Inside the []can either be a literal substring, an index, or a regex:

内部[]可以是文字子字符串、索引或正则表达式:

> s='abcdefg'
=> "abcdefg"
> s['a']
=> "a"
> s['z']
=> nil

Since nilis functionally the same as falseand any substring returned from []is trueyou can use the logic as if you use the method .include?:

由于nil在功能上与false[]is返回的任何子字符串相同,true您可以像使用方法一样使用逻辑.include?

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" has "abc"

0> if s[sub_s]
1>    puts "\"#{s}\" has \"#{sub_s}\""
1> else 
1*    puts "\"#{s}\" does not have \"#{sub_s}\""
1> end
"abcdefg" does not have "xyz" 

Just make sure you don't confuse an index with a sub string:

只要确保不要将索引与子字符串混淆:

> '123456790'[8]    # integer is eighth element, or '0'
=> "0"              # would test as 'true' in Ruby
> '123456790'['8']  
=> nil              # correct

You can also use a regex:

您还可以使用正则表达式:

> s[/A/i]
=> "a"
> s[/A/]
=> nil

回答by Sagar Pandya

How to check whether a string contains a substring in Ruby?

如何在Ruby中检查字符串是否包含子字符串?

When you say 'check', I assume you want a boolean returned in which case you may use String#match?. match?accepts strings or regexes as its first parameter, if it's the former then it's automatically converted to a regex. So your use case would be:

当您说“检查”时,我假设您想要返回一个布尔值,在这种情况下您可以使用String#match?. match?接受字符串或正则表达式作为其第一个参数,如果是前者,则它会自动转换为正则表达式。所以你的用例是:

str = 'string'
str.match? 'strings' #=> false
str.match? 'string'  #=> true
str.match? 'strin'   #=> true
str.match? 'trin'    #=> true
str.match? 'tri'     #=> true

String#match?has the added benefit of an optional second argument which specifies an index from which to search the string. By default this is set to 0.

String#match?具有可选的第二个参数的额外好处,该参数指定从中搜索字符串的索引。默认情况下,这设置为0

str.match? 'tri',0   #=> true
str.match? 'tri',1   #=> true
str.match? 'tri',2   #=> false

回答by Prabhakar Undurthi

user_input = gets.chomp
user_input.downcase!

if user_input.include?('substring')
  # Do something
end

This will help you check if the string contains substring or not

这将帮助您检查字符串是否包含子字符串

puts "Enter a string"
user_input = gets.chomp  # Ex: Tommy
user_input.downcase!    #  tommy


if user_input.include?('s')
    puts "Found"
else
    puts "Not found"
end