ruby gsub string phone conversion into specific format - ruby

i'm trying to convert a phone number using gsub. ""111222333344444" supposed to become "111-222-3333x44444". str.gsub(/^(\d{3})(\d{2,3})(\d{3,4})(\d{4})$/, '\1-\2-\3x\4') returns original string. What am i doing wrong?
Also i converted "W: (111) 222 3333 ext 44") #=> "111-222-3333x44" using the following code. It works, but looks ugly. Is there better way to do it?
if str.split.first == "W:"
first = str.split[1].gsub("(", '').gsub(")", '')
second = str.split[2]
third = str.split[3]
forth = str.split[5]
first + "-" + second + "-" + third + "x" + forth
else

You have 15 numbers but your regex only allows for 14 so it won't match. Specifically you've got 4 digits for the extension, but I think you need 5.
> str.gsub(/^(\d{3})(\d{2,3})(\d{3,4})(\d{5})$/, '\1-\2-\3x\4')
=> "111-222-3333x44444"

Related

How do I use Base64 and exclude special characters +/= from string?

I am currently using Ruby's 'base64' but the strings that are created have special characters like /+= .
How do I remove these and still make sure that my decode works in the future?
Essentially I want alphanumeric to be used.
Rather than invent something new, I'd use Base64.urlsafe_encode64 (and its counterpart Base64.urlsafe_decode64) which is basically base64 with + and / replaced with - and _. This conforms to rfc 4648 so should be widely understandable
If you want alphanumeric, I think it is better and is practical to use base 36. Ruby has built-in encoding/decoding up to base 36 (26 letters and 10 numbers).
123456.to_s(36)
# => "qglj"
"qglj".to_i(36)
# => 123456
class Integer
Base62_digits = [*("0".."9"), *("a".."z"), *("A".."Z")]
def base_62
return "0" if zero?
sign = self < 0 ? "-" : ""
n, res = self.abs, ""
while n > 0
n, units = n.divmod(62)
res = Base62_digits[units] + res
end
sign + res
end
end
p 124.base_62 # => "20"
This could be adapted to handle lower bases, but it may be sufficient as is.

Testing for string containing variable characters in ruby

can i do something like this?
string = "123" + rand(10).to_s + "abc"
=> "1237abc"
string.include?("123" + string.any_character(1) + "abc") # any_character(digit)
=> true
the point is to know a part of a string like lets say a html tag string, testing for something like Name Changes Every Day
and easily find the title from the source every time no matter what it might be, but for me, it will always be one character, soooooo, any help here?
Try that code:
string = "123" + rand(10).to_s + "abc"
string =~ /123\dabc/
0 means that pattern starts at 0 character. This return nil when pattern doesnt match. If you want to match only whole text change /123\dabc/ into /^123\dabc$/
You can just use regular expressions with ruby. Example:
string = "123" + rand(10).to_s + "abc"
string.match /123\dabc/

ruby regex finding first two numbers in a string

If I have a string like
6d7411014f
I want to read the the occurrence of first two integers and put the final number in a variable
Based on above example my variable would contain 67
more examples:
d550dfe10a
variable would be 55
What i've tried is \d but that gives me 6. how do I get the second number?
I'd use scan for this sort of thing:
n = my_string.scan(/\d/)[0,2].join.to_i
You'd have to decide what you want to do if there aren't two numbers though.
For example:
>> '6d7411014f'.scan(/\d/)[0,2].join.to_i
=> 67
>> 'd550dfe10a'.scan(/\d/)[0,2].join.to_i
=> 55
>> 'pancakes'.scan(/\d/)[0,2].join.to_i
=> 0
>> '6 pancakes'.scan(/\d/)[0,2].join.to_i
=> 6
References:
String#scan
Array#[]
Array#join
I really can't answer this exactly in Ruby, but a regex to do it is:
/^\D*(\d)\D*(\d)/
Then you have to concatenate $1 and $2 (or whatever they are called in Ruby).
Building off of sidyll's answer,
string = '6d7411014f'
matched_vals = string.match(/^\D*(\d)\D*(\d)/)
extracted_val = matched_vals[1].to_i * 10 + matched_vals[2].to_i

Ruby replace text within single quotes or backticks for html tag

Hello I am trying to build a simple action in Ruby that takes one string like
result = "This is my javascript variable 'var first = 1 + 1;' and here is another 'var second = 2 + 2;' and that's it!"
So basically I would like to take the text within single quotes ' or backticks ` and and replace it by:
<code>original text</code> note I'm replacing it by an opening and closing code tag
Just like in markdown
so I would have a result like
result = "This is my javascript variable <code>var first = 1 + 1;<code> and here is another <code>var second = 2 + 2;</code> and that's it"
If it's possible to run this natively without the need of any extra gem it would be great :)
Thanks a lot
I guess you'll need to iterate the string and parse it. While you can do non-greedy regex matches, e.g. result.gsub!(/'([^']*)'/, '<code>\1</code>') you might find the result might not behave correctly in corner-cases.
Without any other advanced requirement
>> result.gsub(/\s+'/,"<code>").gsub(/'\s+/,"</code>")
=> "This is my javascript variable<code>var first = 1 + 1;</code>and here is another<code>var second = 2 + 2;</code>and that's it!"
You will need to come-up with a character as a delimiter for your code, which you don't use otherwise..
Why? because of all the corner cases. E.g. the following string
result = "This's my javascript variable 'var first = 1 + 1;' and here is another 'var second = 2 + 2;' and that's it!"
which would otherwise produce:
"This<code>s my javascript variable </code>var first = 1 + 1;<code> and here is another </code>var second = 2 + 2;<code> and that</code>s it!"
Total garbage out..
However if you use a unique character as a delimiter that's otherwise not used, you can create a non-greedy RegExp which will do the search/replace
e.g. using a # character to delimit the code:
"This's my javascript variable #var first = 1 + 1;# and here is another #var second = 2 + 2;# and that's it!"

How do I parse a quoted string inside another string?

I want to extract the quoted substrings from inside a string. This is an example:
string = 'aaaa' + string_var_x + 'bbbb' + string_var_y
The output after parsing should be:
["'aaaa'", "'bbbb'"]
The initial solution was to string.scan /'\w'/ which is almost ok.
Still I can't get it working on more complex string, as it's implied that inside '...' there can be any kind of characters (including numbers, and !##$%^&*() whatever).
Any ideas?
I wonder if there's some way to make /'.*'/ working, but make it less greedy?
Lazy should fix this:
/'.*?'/
Another possibility is to use this:
/'[^']*'/
An alternate way to do it is:
>> %{string = 'aaaa' + string_var_x + 'bbbb' + string_var_y}.scan(/'[^'].+?'/)
#=> ["'aaaa'", "'bbbb'"]
String.scan gets overlooked a lot.

Resources