Check If a String Contains Only Digits in Ruby

Check if a string contains only digits in ruby

You can try the following

def check_string(string)
string.scan(/\D/).empty?
end

It would be truthy if string contains only digits or if it is an empty string. Otherwise returns false.

Check whether a string contains numbers

If its certain that the format of the valid personname is always

<string>.<number>.<string>

You can try using :[regex, index] method for strings in ruby.

https://ruby-doc.org/core-2.6.1/String.html#method-i-5B-5D

So if

personname = "devid.123.devid"

s[/(.*)(\.\d+\.)(.*)/, 2] = ".123."

There are three different groups in the regex (.*)(\.\d+\.)(.*).

  1. Matches anything
  2. Matches a .<number>.
  3. Matches anything

So based on this regex, the second group should provide you .<number>. which, I hope, is what you need.

Tested with Ruby 2.4.1

Check if string contains only positive numbers in Ruby

Of course Regexp is good for this:

string = "123abcd"
/^(?<num>\d+)$/ =~ string
num # => nil

string = "123"
/^(?<num>\d+)$/ =~ string
num # => '123' # String

So if you need to check the condition:

if /^(?<num>\d+)$/ =~ string
num.to_i # => 123
# do something...
end

#to_i method of String isn't valid for your case because it will return a number, if string is even with letters:

string = "123abcd"
string.to_i # 123

Ruby determine if a string only contains numbers

Try this:

def valid_pin?(pin)
/^\d{4}$/ === pin
end

What this is saying basically is:

  1. /^d{4}$/ is a regular expression, you can tell because it is enclosed in / / with a pattern in the middle
  2. the ^ and $ characters denote the beginning and end of your string, respectively. Basically what is ensures is that strings with 4 consecutive numbers but which have other characters at the beginning or end (i.e. "a1234" and "5678b") will not be accepted.
  3. \d is the regular expression character denoting digits. When followed by {4}, this means to look for exactly 4 digits. Ruby also allows you to specify a minimum value using this notation {3,} or a range {3,6}.
  4. The === method (as correctly mentioned by @iamnotmaynard), sometimes called the threequals operator, returns a boolean (true or false) value depending on whether or not the regular expression matches the given string.

In the context of your code:

puts "Please give us a 4 digit pin number for your account:"
@response = gets.chomp

unless valid_pin?(@response)
puts "Your response must be 4 numbers in length."
create_pin
else
@pin = @response.to_i
puts "Your pin has been set."
end

If you want to try and learn about Regular Expressions (commonly referred to as RegExes), I would encourage you to play around on the awesome site Rubular, there is a general keyword list and RegEx sandbox to help you text your creations.

determine if string contains only numbers

I'd use a before_filter before sticking it in every method.

You may also configure a routing segment constraint.

Test if string is a number in Ruby on Rails

Create is_number? Method.

Create a helper method:

def is_number? string
true if Float(string) rescue false
end

And then call it like this:

my_string = '12.34'

is_number?( my_string )
# => true

Extend String Class.

If you want to be able to call is_number? directly on the string instead of passing it as a param to your helper function, then you need to define is_number? as an extension of the String class, like so:

class String
def is_number?
true if Float(self) rescue false
end
end

And then you can call it with:

my_string.is_number?
# => true

How do I check if a string has at least one number in it using Ruby?

You can use the String class's =~ method with the regex /\d/ as the argument.

Here's an example:

s = 'abc123'

if s =~ /\d/ # Calling String's =~ method.
puts "The String #{s} has a number in it."
else
puts "The String #{s} does not have a number in it."
end

Regex pattern to see if a string contains a number in a range

If you don't actually need the number afterwords, and just need to determine yes or no the string contains a number in the range of 400-499, you can:

  1. Check that you are at the beginning of a line, or have a non-digit character followed by
  2. the digit '4' followed by
  3. Any 2 digits followed by
  4. the end of a line or a non-digit character

so you end up with a regex looking something like

regex = /(?:^|\D)4\d{2}(?:\D|$)/

or, by using negative look ahead/look behinds:

regex = /(?<!\d)4\d{2}(?!\d)/

and you need step 1 and 4 above to make rule out numbers such as 1400-1499 and 4000-4999 (and other such numbers with more than 3 digits that have 400-499 somewhere buried in them). You can then make use of String#match? in newer ruby versions to get just a simple boolean:

string.match?(regex)   # => true
string2.match?(regex) # => true
string3.match?(regex) # => false
string4.match?(regex) # => false
"1400".match?(regex) # => false
"400".match?(regex) # => true
"4000".match?(regex) # => false
"[1400]".match?(regex) # => false
"[400]".match?(regex) # => true
"[4000]".match?(regex) # => false

Fairly simple regex, no need to pull out the match and convert it to an integer if you just need a simple yes or no

Validate that string contains only allowed characters in Ruby

This seems to be faster than all previous benchmarks (by @Eric Duminil)(ruby 2.4):

!string.match?(/[^AGHTM0-9]/) 

How can I validate a string only contains specific alpha characters in Ruby?

With regex

input = "ACGTCTTAA"
if input =~ /\A[GCTA]+\z/
# put your code here
end

It means any succession of 'G', 'C', 'T' or 'A's from the beginning to the end of the string.

If an empty string is acceptable, you could use /\A[GCTA]*\z/ instead.

With String#delete

You could also delete every 'G', 'C', 'T' and 'A's with String#delete, and check if the string becomes empty :

"C".delete("GCTA").empty? #=> true
"ACGTXXXCTTAA".delete("GCTA").empty? #=> false
"ACGTCTTAA".delete("GCTA").empty? #=> true
"".delete("GCTA").empty? #=> true


Related Topics



Leave a reply



Submit