我有一个字符串变量,内容如下:
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"
Run Code Online (Sandbox Code Playgroud)
在上面的字符串我必须找到一个子字符串即
"hi/thsid/sdfhsjdf/dfjsd/sdjfsdn\n"
"/my/name/is/balaji.so\n"
"call::myFunction(int const&)\n"
Run Code Online (Sandbox Code Playgroud)
我该怎么找到它?我只需要确定子串是否存在.
Ada*_*ear 1294
您可以使用以下include?方法:
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
Run Code Online (Sandbox Code Playgroud)
Cli*_*chl 83
如果大小写无关紧要,那么不区分大小写的正则表达式是一个很好的解决方案:
'aBcDe' =~ /bcd/i # evaluates as true
Run Code Online (Sandbox Code Playgroud)
这也适用于多行字符串.
请参阅Ruby的Regexp类.
Oto*_*lez 41
你也可以这样做......
my_string = "Hello world"
if my_string["Hello"]
puts 'It has "Hello"'
else
puts 'No "Hello" found'
end
# => 'It has "Hello"'
Run Code Online (Sandbox Code Playgroud)
aci*_*708 30
扩展Clint Pachl的答案:
当表达式不匹配时,Ruby中的正则表达式匹配返回nil.如果是,则返回匹配发生的字符的索引.例如
"foobar" =~ /bar/ # returns 3
"foobar" =~ /foo/ # returns 0
"foobar" =~ /zzz/ # returns nil
Run Code Online (Sandbox Code Playgroud)
值得注意的是,在Ruby中只有nil和布尔表达式false求值为false.其他所有内容(包括空数组,空哈希或整数0)的计算结果为true.
这就是为什么上面的/ foo /示例有效,以及为什么
if "string" =~ /regex/
Run Code Online (Sandbox Code Playgroud)
按预期工作.如果匹配发生,则仅输入if块的"true"部分.
stw*_*667 19
比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
Run Code Online (Sandbox Code Playgroud)
我也认为它更具可读性.
cf http://apidock.com/rails/v3.1.0/Object/in%3F
(请注意,它仅在Rails中可用,而不是纯Ruby.)
Mau*_*uro 16
三元方式
my_string.include?('ahr') ? (puts 'String includes ahr') : (puts 'String does not include ahr')
Run Code Online (Sandbox Code Playgroud)
要么
puts (my_string.include?('ahr') ? 'String includes ahr' : 'String not includes ahr')
Run Code Online (Sandbox Code Playgroud)
daw*_*awg 10
您可以使用String Element Reference方法[]
在[]can 内部可以是文字子字符串,索引或正则表达式:
> s='abcdefg'
=> "abcdefg"
> s['a']
=> "a"
> s['z']
=> nil
Run Code Online (Sandbox Code Playgroud)
因为nil在功能上false和返回的任何子字符串相同,[]所以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"
Run Code Online (Sandbox Code Playgroud)
只需确保不要将索引与子字符串混淆:
> '123456790'[8] # integer is eighth element, or '0'
=> "0" # would test as 'true' in Ruby
> '123456790'['8']
=> nil # correct
Run Code Online (Sandbox Code Playgroud)
你也可以使用正则表达式:
> s[/A/i]
=> "a"
> s[/A/]
=> nil
Run Code Online (Sandbox Code Playgroud)