I got a variable string which equals shid!
I'd like a regular expression that renders true if the inputed string matches every character of the previous variable string in the good order.
As I always fail to explain properly what I want to do, here is an example of possible inputs and outputs:
shid! returns true
shid returns false
shhhhiddd! returns true
ssssshhhhiiiiiddd!!!! returns true
hsid! returns false
For the ritual question "What did I try", I'm not used to regular expression. So my answer would be this: "shid!" =~ /s.*!/, and obviouly this isn't the good answer and I know why, but don't know how to fix it. Thanks for the kind help
Try:
string = 'shid!'
reg = Regexp.new string.split('').join('+')
!!('shid!' =~ reg) #=> true
!!('shid' =~ reg) #=> false
!!('shhhhiddd!' =~ reg) #=> true
!!('ssssshhhhiiiiiddd!!!!' =~ reg) #=> true
!!('hsid!' =~ reg) #=> false
You can do using #squeeze
str.squeeze == 'shid!' #=> true
I'm not sure I've got the question. But maybe it's what you are looking for:
str = 'ssssshhhhiiiiiddd!!!!'
str.split('').uniq.join == 'shid!' #=> true
Related
I am new to ruby, I am trying to write a method that checks if the word includes "hello" case insensitive e.g "HelLO" would still be true.
I can think of two approaches:
downcase before comparing
str = "HelLO"
str.downcase.include?('hello')
#=> true
use case-insensitive regular rexpression
str = "HelLO"
str.match?(/hello/i)
#=> true
I think the easiest approach is to downcase both string and do the comparing. Like this:
'HellO'.downcase.include?('hello')
# true
So far I have:
def capitalized?(str)
str[0] == str[0].upcase
end
THe problem wit this is that it returns true for strings like "12345", "£$%^&" and"9ball" etc. I would like it to only return true if the first character is a capital letter.
You can use match? to return true if the first character is a letter in the range of A to Z both uppercase or not:
def capitalized?(str)
str.match?(/\A[A-Z]/)
end
p capitalized?("12345") # false
p capitalized?("fooo") # false
p capitalized?("Fooo") # true
Also you can pass a regular expression to start_with?:
p 'Foo'.start_with?(/[A-Z]/) # true
p 'foo'.start_with?(/[A-Z]/) # false
There's probably a nicer way to do it with regex, but keeping this ruby based, you can make an array of capital letters:
capital_letters = ("A".."Z")
Then you can check if your first letter is in that array:
def capitalized?(str)
capital_letters = ("A".."Z")
capital_letters.include?(str[0])
end
Or a bit shorter:
def capitalized?(str)
("A".."Z").include?(str[0])
end
I would avoid character ranges if possible, because without knowing the encoding, you can never be sure what is in a range. In your case, it is unnecessary. A simple
/^[[:upper:]]/ =~ str
would do. See here for the definition of POSIX character classes.
def capitalized?(str)
str[0] != str[0].downcase
end
capitalized? "Hello" #=> true
capitalized? "hello" #=> false
capitalized? "007, I presume" #=> false
capitalized? "$100 for that?" #=> false
Simple solution
def capitalized?(str)
str == str.capitalize
end
I want to check if a string is made of only numbers and letters.
def valid?
"abc#d" =~ /\p{Alnum}/
end
But this returns 0. I expect it to return nil since it contains # which is neither a letter nor a number.
What am I doing wrong?
What is wrong is that you are actually checking:
whether a string contains any number or letter,
but you wanted to check:
whether a string does not contain anything other than a number or letter.
You can check it like this:
def valid?
"abc#d" !~ /\P{Alnum}/
end
It sounds like you want to check to make sure that the string contains only numbers and letters:
"abc#d" =~ /\A\p{Alnum}+\z/
Try with this:
"abc#d" =~ /^[A-Za-z0-9]+$/
string !~ /[_\W]/ also works.
"abc#d" !~ /[_\W]/ #=> false
"abc_d" !~ /[_\W]/ #=> false
"abc5d" !~ /[_\W]/ #=> true
I have a string which should ONLY be made up of 0 and 1. If the string has any other characters (including special characters) then the validation should return false; otherwise it should return a true.
How can I achieve this?
Use Regexp#===
s = '11er0'
# means other character present except 1 and 0
/[^10]/ === s # => true
s = '1100'
# means other character not present except 1 and 0
/[^10]/ === s # => false
Here is a method :
def only_1_and_0(s)
!(/[^10]/ === s)
end
only_1_and_0('11012') # => false
only_1_and_0('1101') # => true
try this:
def only_0_and_1(str)
return !!(str =~ /^(0|1)+$/)
end
The following assumes your method will always receive a string; it doesn't perform any coercion or type checking. Feel free to add that if you need it.
def binary? str
! str.scan(/[^01]/).any?
end
This will scan the string for any characters other than zero or one using String#scan, and then returns an inverted Boolean that evaluates to false if Enumerable#any? is true, meaning that other characters are present in the string. For example:
binary? '1011'
#=> true
binary? '0b1011'
#=> false
binary? '0xabc'
#=> false
Another way to do it:
str.chars.any?{|c| c!='0' && c!='1'}
def binary?
str.count("^01").zero?
end
This code:
/ell/ === 'Hello'
evalutes to 'true' in IRB.
I don't understand why this makes sense logically. Integer === 30 makes sense because 30 is a PART OF the Integer class, but in what way is the string 'Hello' a PART OF /ell/? I don't get it.
Semantically you're saying does the regular expression 'ell' match the string 'Hello'. Since 'Hello' contains the substring 'ell', it is true.
The '===' method is described here:
http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-i-3D-3D-3D
You should not use === for anything in ruby except case equality, find the documentation on Regex#===
Following a regular expression literal with the === operator allows you to compare against a String.
/^[a-z]$/ === "HELLO" #=> false
/^[A-Z]$/ === "HELLO" #=> true
The === the case operator, it is primarily used in case statements and should not really be seen by its own.
case my_string
when /ll/ then puts 'the string migth be hello'
when /x/ then puts 'all i know is that the sting contain x'
else puts 'I have no idea'
end
It can also be used in some other functions such as grep:
array = ['ll', 'aa', 'hello']
p array.grep(/ll/){|x| x.upcase} #=> ["LL", "HELLO"]
Any other use is discouraged and it really does not need to make any sense.
A regular expression describes a language, i.e. a set of strings. The === checks whether the string is a member of that set.
See my answer to a similar question for details.