what is the difference between gsub using / or "? - ruby-on-rails

I am trying to use gsub to replace "?" and "." with empty space.
I realize that is a difference between gsub(".", "") and gsub(/./, ""), but I don't know what it is. Can Someone explain?
Also, gsub("?","") seems to work, and gsub(/?/,"") doesn't work.
How can we make gsub(/?/,"") work?

gsub("?", "") matches a literal ?, while gsub(/?/, "") uses regular expressions to find a match. And in regular expressions, the ? means that the previous character can be present either 0 or 1 times. In order to match a literal ?, you have to escapte it:
gsub(/\?/, "")
See also the ruby documentation about gsub

Finally as it mentioned above /reg/ represents regexp when "str" represents just a string. Your aim is to remove ? and . from a string. Regexp will do the job:
gsub(/[?.]/, '')
You can read more about ruby regexp here. In my example /[abc]/ will match single character a or b or c.

The former is to literally find "?" characters and replace them, while the latter is to find occurrences of 0 or 1 of a given character. ? has a special meaning for regular expressions, which you delimit using /.

Related

Ruby Convert string into undescore, avoid the "/" in the resulting string

I have a name spaced class..
"CommonCar::RedTrunk"
I need to convert it to an underscored string "common_car_red_trunk", but when I use
"CommonCar::RedTrunk".underscore, I get "common_car/red_trunk" instead.
Is there another method to accomplish what I need?
Solutions:
"CommonCar::RedTrunk".gsub(':', '').underscore
or:
"CommonCar::RedTrunk".sub('::', '').underscore
or:
"CommonCar::RedTrunk".tr(':', '').underscore
Alternate:
Or turn any of these around and do the underscore() first, followed by whatever method you want to use to replace "/" with "_".
Explanation:
While all of these methods look basically the same, there are subtle differences that can be very impactful.
In short:
gsub() – uses a regex to do pattern matching, therefore, it's finding any occurrence of ":" and replacing it with "".
sub() – uses a regex to do pattern matching, similarly to gsub(), with the exception that it's only finding the first occurrence (the "g" in gsub() meaning "global"). This is why when using that method, it was necessary to use "::", otherwise a single ":" would have been left. Keep in mind with this method, it will only work with a single-nested namespace. Meaning "CommonCar::RedTrunk::BigWheels" would have been transformed to "CommonCarRedTrunk::BigWheels".
tr() – uses the string parameters as arrays of single character replacments. In this case, because we're only replacing a single character, it'll work identically to gsub(). However, if you wanted to replace "on" with "EX", for example, gsub("on", "EX") would produce "CommEXCar::RedTrunk" while tr("on", "EX") would produce "CEmmEXCar::RedTruXk".
Docs:
https://apidock.com/ruby/String/gsub
https://apidock.com/ruby/String/sub
https://apidock.com/ruby/String/tr
This is a pure-Ruby solution.
r = /(?<=[a-z])(?=[A-Z])|::/
"CommonCar::RedTrunk".gsub(r, '_').downcase
#=> "common_car_red_trunk"
See (the first form of) String#gsub and String#downcase.
The regular expression can be made self-documenting by writing it in free-spacing mode:
r = /
(?<=[a-z]) # assert that the previous character is lower-case
(?=[A-Z]) # assert that the following character is upper-case
| # or
:: # match '::'
/x # free-spacing regex definition mode
(?<=[a-z]) is a positive lookbehind; (?=[A-Z]) is a positive lookahead.
Note that /(?<=[a-z])(?=[A-Z])/ matches an empty ("zero-width") string. r matches, for example, the empty string between 'Common' and 'Car', because it is preceeded by a lower-case letter and followed by an upper-case letter.
I don't know Rails but I'm guessing you could write
"CommonCar::RedTrunk".delete(':').underscore

string regex on ruby on rails

how to make sure my string format must be like this :
locker_number=3,email=ucup#gmail.com,mobile_phone=091332771331,firstname=ucup
i want my string format `"key=value,"
how to make regex for check my string on ruby?
This regex will find what you're after.
\w+=.*?(,|$)
If you want to capture each pairing use
(\w+)=(.*?)(?:,|$)
http://rubular.com/r/A2ernIzQkq
The \w+ is one or more occurrences of a character a-z, 1-9, or an underscore. The .*? is everything until the first , or the end of the string ($). The pipe is or and the ?: tells the regex no to capture that part of the expression.
Per your comment it would be used in Ruby as such,
(/\w+=.*?(,|$)/ =~ my_string) == 0
You can use a regex like this:
\w+=.*?(,|$)
Working demo
You can use this code:
"<your string>" =~ /\w+=.*?(,|$)/
What about something like this? It's picky about the last element not ending with ,. But it doesn't enforce the need for no commas in the key or no equals in the value.
'locker_number=3,email=ucup#gmail.com,mobile_phone=091332771331,firstname=ucup' =~ /^([^=]+=[^,]+,)*([^=]+=[^,]+)$/

Regex in Ruby not working

I have a string from which I want to extract a certain part:
Original String: /abc/d7_t/g-12/jkl/m-n3/pqr/stu/vwx
Result Desired: /abc/d7_t/g-12/jkl/
The number of characters can vary in the entire string. It has alphabets, numbers, underscore and hyphen. I want to basically cut the string after the 5th "/"
I tried a few regex, but it seems there is some mistake with the format.
If a non-regexp approach is acceptable, how about this:
s.split('/').take(n).join('/')+'/'
Where s if your string (in your case: /abc/d7_t/g-12/jkl/m-n3/pqr/stu/vwx).
def cut_after(s, n)
s.split('/').take(n).join('/')+'/'
end
Then
cut_after("/abc/d7_t/g-12/jkl/m-n3/pqr/stu/vwx", 5)
should work. Not as compact as a regexp, but some people may find it clearer.
The regexp would be: %r(/(?:[^/]+/){4}). Note that it is a good idea in this case to use the %r literal version to avoid escaping slashes. Unescaped slashes are likely the cause of your format errors.
Match any sequence of chars except '/' 4 times :-
(\/[^\/]+){4}\/

Removing lines that begin with > in a rails string

I'm trying to remove any lines that begin with the character '>' in a long string (i.e. replies to an email).
In PHP I'd iterate over each line with an if statement, in linux I'd try and use sed or awk.
What's the most elegant rails approach?
You can try this:
your_string.gsub(/^\>.+\n/,'')
Your question is implying that the input is one string, containing multiple lines.
Do you want the output to be just one string with multiple lines as well? I'm assuming yes.
either using String and Array operations:
str.lines.reject{|x| x =~ /^>/}.join # this will return a new string, without those ">" lines
or using Regular Expressions:
str.gsub(/^>.+\n*/. '')
Better Solution:
You will need to use non-greedy multi-line matching mode for your Regular Expression:
str.gsub(/^>.*?$\n*/m, '') # by using gsub!() you can modify the string in place
^> matches your ">" character at the start of a line
.*?$ matches any characters after the start character until the end of the line (non-greedy)
\n* matches the newline character itself if any (you want to remove that as well)
the "m" at the end of the regular expressions indicates multi-line matching , which will apply the RegExp for each line in the string.
It should work as you expect:
your_string.lines.to_a.reject{|line| line[0] == '>'}.join

Regular expression in Ruby

Could anybody help me make a proper regular expression from a bunch of text in Ruby. I tried a lot but I don't know how to handle variable length titles.
The string will be of format <sometext>title:"<actual_title>"<sometext>. I want to extract actual_title from this string.
I tried /title:"."/ but it doesnt find any matches as it expects a closing quotation after one variable from opening quotation. I couldn't figure how to make it check for variable length of string. Any help is appreciated. Thanks.
. matches any single character. Putting + after a character will match one or more of those characters. So .+ will match one or more characters of any sort. Also, you should put a question mark after it so that it matches the first closing-quotation mark it comes across. So:
/title:"(.+?)"/
The parentheses are necessary if you want to extract the title text that it matched out of there.
/title:"([^"]*)"/
The parentheses create a capturing group. Inside is first a character class. The ^ means it's negated, so it matches any character that's not a ". The * means 0 or more. You can change it to one or more by using + instead of *.
I like /title:"(.+?)"/ because of it's use of lazy matching to stop the .+ consuming all text until the last " on the line is found.
It won't work if the string wraps lines or includes escaped quotes.
In programming languages where you want to be able to include the string deliminator inside a string you usually provide an 'escape' character or sequence.
If your escape character was \ then you could write something like this...
/title:"((?:\\"|[^"])+)"/
This is a railroad diagram. Railroad diagrams show you what order things are parsed... imagine you are a train starting at the left. You consume title:" then \" if you can.. if you can't then you consume not a ". The > means this path is preferred... so you try to loop... if you can't you have to consume a '"' to finish.
I made this with https://regexper.com/#%2Ftitle%3A%22((%3F%3A%5C%5C%22%7C%5B%5E%22%5D)%2B)%22%2F
but there is now a plugin for Atom text editor too that does this.

Resources