Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Is there something in Ruby that returns true only if the string contains the whole word, in this case 'hello'?
I don't want the behavior of include? which returns true if only some characters within a word are present:
'hello whats up'.include? 'll'
=> true
> 'hownowbrowncow'['now'] => "now" # will be nil if not found
And if you want it to require word boundaries...
'hownowbrowncow'[/\bnow\b/] => nil
It doesn't really matter if it returns true or false, since anything other than nil or false will fulfill a conditional test. If you really like true and false, well, you can turn an arbitrary expression into true or false a number of ways, one way is:
'now'.nil? => false
!'now'.nil? => true
Lots of good ways to do this as others have given. Here's another way:
my_string.scan(/\w+/).include? "hello"
This would be a case-sensitive check. For case insensitive:
my_string.scan(/\w+/).map(&:downcase).include? "hello"
This will also work with a variable for "hello":
m_string.scan(/\w+/).map(&:downcase).include? my_word
str = "Hello guys, how are you?'"
keyword = "hello"
print str.split.map { |word| word.downcase }.include? keyword.downcase
If you mean only the alphabet, then you could
(! 'Wr4ngle'.gsub(/[A-Za-z]/, '').blank?)
That grep should be versatile enough for your needs
It sounds like you're asking to simply do:
"hello" == "hello"
If you don't want the match to be case sensitive, you could use:
"HeLlO".downcase == "hElLo".downcase
If you are looking to see if a string of characters includes another string of characters, you could do something like this:
s1 = "hello"
s2 = "oelhl"
s1.split("").sort == s2.split("").sort #=> case sensitive
s1.downcase.split("").sort == s2.downcase.split("").sort #=> not case sensitive
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
I got to solve the problem I was trying to solve, but the thing is that I am not sure why it worked, I just started adding methods.
So if anyone could explain why worked:
def replace(string1, letter_a, letter_b)
replacements = {letter_a => letter_b}
#this is the part I am not sure why is working:
initial_string.split('').map{|i| replacements[i] || i}.join
end
Firstly I recommend to use built-in methods String#gsub or String#tr
string.gsub(%r{#{replaceable_letter}}, replacing_letter)
"abcdef".gsub(/a/, "b") # => "bbcdef"
string.tr(replaceable_letter, replacing_letter)
"abcdef".tr("a", "b") # => "bbcdef"
Instead of initial_string.split('').map you can use initial_string.each_char.map
Explanation of your code:
replacements = {letter_a => letter_b}
is hash where replaceable letter is key and replacing letter is value
For example { "a" => "b" }
Than you split your string to chars array
After that map over this array
For every char you check the hash, for example:
replacements["a"] # => "b"
replacements["c"] # => nil
If hash has such key, you take replacing letter, if not take origin letter. Compare and read about || operator:
nil || "f" # => "f"
"b" || "a" # => "b"
And finally join new array
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to see if any arbitrary characters c1,c2,c3... turn up in a given string.
I'm looking for a nice way to rework the following example:
val = String.new("abc123")
if val.include? "a" or val.include? "2" or val.include? "3"
...
end
Try something like this
arr = [ 'a', '2', '3' ]
s = "abc123"
arr.any? { |letter| s.include? letter } # Will return true if any element is present
I would use a regular expression.
string_to_check = "hello random abc123"
string_to_check =~ /[a23]/
That would return the position where the first match is. Then if you would want to know if it is true or false you could just do == 0 or != 0
(string_to_check =~ /[a23]/) != 0
Write as below :
val = "abc123"
val[/[1af]/] # => "a"
val[/[w6f]/] # => nil
So change your code as
if val[/[a23]/]
#...
end
See the documentation of str[regexp] → new_str or nil.
If a Regexp is supplied, the matching portion of the string is returned. If a capture follows the regular expression, which may be a capture group index or name, follows the regular expression that component of the MatchData is returned instead.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose I have a list of characters [a,b,c] and I want to write a regular expression such that
any string is accepted if it has all the elements in the character list at-least once and the characters can appear in any order in the string.
Example of accepted strings
abc, aabbbc, bbaac, cab
Example of strings not accepteed
aaabb, bab, caa, aacd, deeff
Sets are much more suited for this purpose than regular expressions. What you're really trying to do is find out if (a, b, c) is a valid subset of your various strings. Here's an example of how to do that in Ruby:
> require "set"
=> true
> reference = Set.new("abc".split(""))
=> #<Set: {"a", "b", "c"}>
> test1 = Set.new("aabbbc".split(""))
=> #<Set: {"a", "b", "c"}>
> test2 = Set.new("caa".split(""))
=> #<Set: {"c", "a"}>
> reference.subset? test1
=> true
> reference.subset? test2
=> false
Consider this before reading on: regexes are not always the best way to solve a problem. If you are considering a regex but it's not obvious or easy to proceed, you may want to stop and consider if there is an easy non-regex solution handy.
I don't know what your specific situation is or why you think you need regex, so I'll assume you already know the above and answer your question as-is.
Based on the documentation, I beleive that Ruby supports positive lookaheads (also known as zero-width assertions). Being primarily a .NET programmer, I don't know Ruby well enough to say whether or not it supports non-fixed-length lookaheads (it's not found in all regex flavors), but if it does then you can easily apply three different lookaheads at the beginning of your expression to find each of the patterns or characters you need:
^(?=.*a)(?=.*b)(?=.*c).*
This will fail if any one of the lookaheads does not pass. This approach is potentially extremely powerful because you can have complex sub expressions in your lookahead. For example:
^(?=.*a[bc]{2})(?=.*-\d)(?=.*#.{3}%).*
will test that the input contains an a follwed by two characters which are each either a b or a c, a - followed by any digit and a # followed by any three characters followed by a %, in any particular order. So the following strings would pass:
#acb%-9
#-22%abb
This kind of complex pattern matching is difficult to succinctly duplicate.
To address this comment:
No there cannot be... so abcd is not accepted
You can use a negative lookahead to ensure that characters other than the desired characters are not present in the input:
^(?=.*a)(?=.*b)(?=.*c)(?!.*[^abc]).*
(As noted by Gene, the .* at the end is not necessary... I probably should have mentioned that. It's just there in case you actually want to select the text)
def acceptable? s
s =~ /(?=.*a)(?=.*b)(?=.*c)/
end
acceptable? 'abc' # => 0
acceptable? 'aabbbc' # => 0
acceptable? 'bbaac' # => 0
acceptable? 'cab' # => 0
acceptable? 'aaabb' # => nil
acceptable? 'bab' # => nil
acceptable? 'caa' # => nil
acceptable? 'aacd' # => nil
acceptable? 'deeff' # => nil
acceptable? 'abcd' # => 0
A regex that matches only the defined characters could be this:
(?=[bc]*a)(?=[ac]*b)(?=[ab]*c)[abc]*
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to match a pattern as given below
pattern: file.update.20120304.xml
file.update.1.xml
file.update.201203040002.xml
If i have to match the pattern leaving the numbers file.update..xml
how can I do in ruby?
"file.update.20120304.xml"[/\d+/] # => "20120304"
"file.update.1.xml"[/\d+/] # => "1"
"file.update.201203040002.xml"[/\d+/] # => "201203040002"
You can use Regexp and gsub to extract the numbers
filename = 'file.update.20120304.xml'
numbers = filename.gsub(/\Afile\.update\.(\d+)\.xml\z/, '\1')
The used regexp is composed as following:
a first part file\.update\. to be sure you have "file.update"
a middle part ([0-9]+) to have one or more number
an end part \.xml to be sure to have ".xml" at the end
the anchors \A and \z for the beginning and the end of the string
The middle part is wrapped with () to be a Regexp variable that you can reuse in the replacement string as \1
Update with variableName[/regular expression/]
filename = 'file.update.20120304.xml'
numbers = filename[/\Afile\.update\.(\d+)\.xml\z/, 1]
It returns the first captured group, i.e. between ().
p "file.update.201203040002.xml".split(".") .map { |x| x if x.to_i != 0}.compact[0].to_i
#=> 201203040002
p "file.update.20120304.xml".split(".") .map { |x| x if x.to_i != 0}.compact[0].to_i
#=> 20120304
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm using Ruby to do a simple substring type match. I'm trying to understand why the following happens:
irb(main):024:0> puts "match" if "foo" =~ /foo/
match
=> nil
irb(main):025:0> puts "match" if "foo" =~ /foo,/
=> nil
how can this regex be modified so that if any part of the search criteria matches "foo", a match is made?
You've got your comparisons backwards:
"foo".match(/foo,/) # See if "foo" matches the pattern "foo,"
# => nil
"foo,".match(/foo/) # See if "foo," matches the pattern "foo"
# => #<MatchData "foo">
The =~ operator is a bit of history that has fallen out of style because it's not self-explanatory.
You can use the scan method of String and pass in the regex you want to check against.
1.9.3p194 :008 > puts "match" if "foo".scan(/foo,/)
match
=> nil