如何检查一个字符串是否包含Ruby中的子字符串?

时间:2021-02-18 07:22:15

I have a string variable with content as follows:

我有一个字符串变量,内容如下:

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 above string i have to find a sub string i.e.

在上面的字符串中,我必须找到一个子字符串。

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


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

How can I find it? I just need to determine whether the substring is present or not.

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

9 个解决方案

#1


1052  

You can use the include? method:

你可以使用include?方法:

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

#2


66  

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

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

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

This will also work for multi-line strings.

这也适用于多行字符串。

See Ruby's Regexp class.

看到Ruby的Regexp类。

#3


32  

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"'

#4


24  

Expanding on Clint Pachl's answer:

扩展到克林特·帕赫特的回答:

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

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

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

It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty array, empty hash, or the integer 0, evaluates to true.

值得注意的是,在Ruby中,只有nil和布尔表达式假的值为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 if block if a match occurred.

像预期的那样工作。只有当匹配发生时才进入if块的“true”部分。

#5


13  

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')

#6


12  

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到以上)中,有一个更简洁的表达方式(从3.1.0到以上)。

E.g:

例句:

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.

我也认为它更有可读性。

c.f. http://apidock.com/rails/v3.1.0/Object/in%3F

多严峻http://apidock.com/rails/v3.1.0/Object/in%3F

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

(注意,它只在Rails中可用,而不是纯Ruby。)

#7


3  

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

#8


3  

You can use the String Element Reference method 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 nil is functionally the same as false and any substring returned from [] is true you can use the logic as if you use the method .include?:

由于nil在功能上与false相同,并且从[]返回的任何子字符串都是正确的,所以您可以使用逻辑,就像您使用该方法一样。

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:

你也可以使用regex:

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

#9


0  

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:

当你说'check'时,我假设你想要一个布尔值,在这种情况下,你可以使用String#match?比赛吗?接受字符串或regexes作为它的第一个参数,如果它是前者,那么它将自动转换为regex。所以用例是:

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.

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

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

#1


1052  

You can use the include? method:

你可以使用include?方法:

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

#2


66  

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

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

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

This will also work for multi-line strings.

这也适用于多行字符串。

See Ruby's Regexp class.

看到Ruby的Regexp类。

#3


32  

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"'

#4


24  

Expanding on Clint Pachl's answer:

扩展到克林特·帕赫特的回答:

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

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

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

It's important to note that in Ruby only nil and the boolean expression false evaluate to false. Everything else, including an empty array, empty hash, or the integer 0, evaluates to true.

值得注意的是,在Ruby中,只有nil和布尔表达式假的值为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 if block if a match occurred.

像预期的那样工作。只有当匹配发生时才进入if块的“true”部分。

#5


13  

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')

#6


12  

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到以上)中,有一个更简洁的表达方式(从3.1.0到以上)。

E.g:

例句:

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.

我也认为它更有可读性。

c.f. http://apidock.com/rails/v3.1.0/Object/in%3F

多严峻http://apidock.com/rails/v3.1.0/Object/in%3F

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

(注意,它只在Rails中可用,而不是纯Ruby。)

#7


3  

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

#8


3  

You can use the String Element Reference method 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 nil is functionally the same as false and any substring returned from [] is true you can use the logic as if you use the method .include?:

由于nil在功能上与false相同,并且从[]返回的任何子字符串都是正确的,所以您可以使用逻辑,就像您使用该方法一样。

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:

你也可以使用regex:

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

#9


0  

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:

当你说'check'时,我假设你想要一个布尔值,在这种情况下,你可以使用String#match?比赛吗?接受字符串或regexes作为它的第一个参数,如果它是前者,那么它将自动转换为regex。所以用例是:

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.

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

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