Find and extract string from text? - ruby-on-rails

I am building a Rails 5.2 app.
In this app I parse incoming emails. In each email there is a tag connecting it to another object within the system.
It looks like this:
[Invitation_77decd78-0f77-46df-ae1c-e49f45a2a3ee]
Please note that both Invitation and 77decd78-0f77-46df-ae1c-e49f45a2a3ee are dynamic.
But the [] are always there, encapsulating the substring.
How can I find the above string and then extract it from a longer text (the email body)?

You may use a regex approach with a capture group:
s = "blah blah [Invitation_77decd78-0f77-46df-ae1c-e49f45a2a3ee] blah"
output = s.match(/\[\w*(\w{6}(?:-\w{4}){3}-\w{12})\]/)[1]
puts output # decd78-0f77-46df-ae1c-e49f45a2a3ee
To also capture the portion leading up to the UUID, add another capture group:
output = s.match(/\[(\w+)_\w*(\w{6}(?:-\w{4}){3}-\w{12})\]/)
puts output[1] # Invitation
puts output[2] # decd78-0f77-46df-ae1c-e49f45a2a3ee

Related

Rails application with regular expression validation

I have created an application like users app using rails. In this app, the text file is imported to DB. In which, i need to validate the mobile number, that means, it should not contains + or * or any other special characters, suppose if it presence it should neglect this special characters and print the rest. I have used the following code to store the text file in array.
File.open('text file') do |f|
while line = f.gets
array = line.split(',')
user = User.new
user.user_name = array[0]
user.email_id = array[1]
user.mobile_number = array[2]
user.save
end
Use global substitute using regex, to remove the non-number part.
user.mobile_number = array[2].gsub(/[^0-9]/,'')

changing a variable using gets.chomp()

im trying to write to a file using this code:
puts "-------------------- TEXT-EDITOR --------------------"
def tor(old_text)
old_text = gets.chomp #
end
$epic=""
def torr(input)
tore= $epic += input + ", "
File.open("tor.txt", "w") do |write|
write.puts tore
end
end
loop do
output = tor(output)
torr(output)
end
i have read the ultimate guide to ruby programming
and it says if i want to make a new line using in the file im writing to using File.open
i must use "line one", "line two
how can i make this happend using gets.chomp()? try my code and you will see what i mean
thank you.
The gets method will bring in any amount of text but it will terminate when you hit 'Enter' (or once the STDIN receives \n). This input record separator is stored in the global variable $/. If you change the input separator in your script, the gets method will actually trade the 'Enter' key for whatever you changed the global variable to.
$/ = 'EOF' # Or any other string
lines = gets.chomp
> This is
> multilined
> textEOF
lines #=> 'This is\nmultilined\ntext'
Enter whatever you want and then type 'EOF' at the end. Once it 'sees' EOF, it'll terminate the gets method. The chomp method will actually strip off the string 'EOF' from the end.
Then write this to your text file and the \n will translate into new lines.
File.open('newlines.txt', 'w') {|f| f.puts lines}
newlines.txt:
This is
multilined
text
If you dont use .chomp() the \n character will be added whenever you write a new line, if you save this to the file it also will have a new line. .chomp() removes those escape characters from the end of the input.
If this doesnt answer your question, i am sorry i dont understand it.

Stop parsing when hitting an empty line

I have a Rails app parsing incoming e-mails on Heroku using the Cloud-mailin add-on. The app recieves a list of prices in an e-mail and inserts them into the database.
This works fine, but if the e-mail contains for instance a signature in the bottom the code fails because it's also trying to parse that text.
Therefor I would like to rewrite the below parsing code to stop when it hits an empty line in the e-mail. All the price data is always at the top of the e-mail.
email_text = params[:plain]
email_text_array = []
email_text.split("\n").each do |email_line|
email_text_array << email_line.split(" ")
end
How do I change the above to stop when it hits an empty line in the email_taxt variable?
Thanks!
You can add a break :
email_text.split("\n").each do |email_line|
break if email_line.blank? # ends loop on first empty line
email_text_array << email_line.split(" ")
end
Does this question help: Is there a "do ... while" loop in Ruby?
Edit 1:
From the above article I think something like this would work:
email_text.split("\n").each do |email_line|
break if email_line.length < 1
email_text_array << email_line.split(" ")
end

Generate a link_to on the fly if a URL is found inside the contents of a db text field?

I have an automated report tool (corp intranet) where the admins have a few text area boxes to enter some text for different parts of the email body.
What I'd like to do is parse the contents of the text area and wrap any hyperlinks found with link tags (so when the report goes out there are links instead of text urls).
Is ther a simple way to do something like this without figuring out a way of parsing the text to add link tags around a found (['http:','https:','ftp:] TO the first SPACE after)?
Thank You!
Ruby 1.87, Rails 2.3.5
Make a helper :
def make_urls(text)
urls = %r{(?:https?|ftp|mailto)://\S+}i
html_text = text.gsub urls, '\0'
html_text
end
on the view just call this function , you will get the expected output.
like :
irb(main):001:0> string = 'here is a link: http://google.com'
=> "here is a link: http://google.com"
irb(main):002:0> urls = %r{(?:https?|ftp|mailto)://\S+}i
=> /(?:https?|ftp|mailto):\/\/\S+/i
irb(main):003:0> html = string.gsub urls, '\0'
=> "here is a link: http://google.com"
There are many ways to accomplish your goal. One way would be to use Regex. If you have never heard of regex, this wikipedia entry should bring you up to speed.
For example:
content_string = "Blah ablal blabla lbal blah blaha http://www.google.com/ adsf dasd dadf dfasdf dadf sdfasdf dadf dfaksjdf kjdfasdf http://www.apple.com/ blah blah blah."
content_string.split(/\s+/).find_all { |u| u =~ /^https?:/ }
Which will return: ["http://www.google.com/", "http://www.apple.com/"]
Now, for the second half of the problem, you will use the array returned above to subsititue the text links for hyperlinks.
links = ["http://www.google.com/", "http://www.apple.com/"]
links.each do |l|
content_string.gsub!(l, "<a href='#{l}'>#{l}</a>")
end
content_string will now be updated to contain HTML hyperlinks for all http/https URLs.
As I mentioned earlier, there are numerous ways to tackle this problem - to find the URLs you could also do something like:
require 'uri'
URI.extract(content_string, ['http', 'https'])
I hope this helps you.

Given a list of emails, how to determine if a email exists

Given a string like x#gmail.com, b#yahoo.com, c#ebay.com
How can I, using ruby, see if the string contains c#ebay.com ?
emails = "sam#sam.com, samuelgilman#samuelgilman.com, etc..."
emails.include?('sam#sam.com')
$ true
emails.include?(s#s.com)
$false
update
If you want to pass multiple emails to include you can use the following code if you are using ruby 1.9.2:
emails.include?(email1 || email2)
As for ruby version below that you could do something like this:
emails = "sam#sam.com, samuelgilman#samuelgilman.com, etc..."
emails_to_check = [email1, email2]
emails_to_check.each do |email|
return true if emails.include(email)
end
Since emails is a string it poses some problems. You can create an array or emails to check the string by with an each method but your code seems to be as good if not better.

Resources