Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all digits from string regexp ruby

Tags:

How to get all the digits from a sentence string like "Lorem 123 ipsum 456 879" => "123456879" using regexp in ruby?

like image 337
user1030981 Avatar asked Nov 05 '11 10:11

user1030981


People also ask

What does =~ mean in Ruby regex?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

How do you get an integer from a string in Ruby?

To convert an string to a integer, we can use the built-in to_i method in Ruby. The to_i method takes the string as a argument and converts it to number, if a given string is not valid number then it returns 0.

How do you match a string in Ruby?

Ruby | Regexp match() functionRegexp#match() : force_encoding?() is a Regexp class method which matches the regular expression with the string and specifies the position in the string to begin the search. Return: regular expression with the string after matching it.


1 Answers

Just replace everything else.

result = subject.gsub(/[^\d]/, '') 
like image 155
FailedDev Avatar answered Oct 03 '22 06:10

FailedDev