Replace & to \& in Ruby seems impossible?
Your linked question provides a solution - use the block form of gsub
:
irb(main):009:0> puts "asdf & asdf".gsub("&"){'\&'}
asdf \& asdf
How to replace & with \& with gsub on rails?
Use triple \
in the replacement string:
print 'Company & Co. KG'.gsub('&', '\\\&')
# Company \& Co. KG=> nil
You can check that a single backslash is added by checking the length of both strings:
'Company & Co. KG'.size
# => 16
'Company & Co. KG'.gsub('&', '\\\&').size
# => 17
To understand it better, read about escaping:
- https://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes
- https://gist.github.com/kbaribeau/1103102
- Weird backslash substitution in Ruby
EDIT:
\&
is a backreference to the whole match (like \0
)
'Company & Co. KG'.gsub(/Co/, '-\&-')
# => "-Co-mpany & -Co-. KG"
'Company & Co. KG'.gsub(/Co/, '-\0-')
# => "-Co-mpany & -Co-. KG"
How to replace single quote to backslash in ruby?
Ruby is interpreting the \'
as a backreference to the post-match string($'). So, you are replacing the quote with everything after the quote:
<space>DROP TABLE Suppliers
V
"105;' DROP TABLE Suppliers"
Here it is with a backreference to the pre-match variable($`):
string = "105;' DROP TABLE Suppliers"
new_string = string.gsub("'", %q(\`))
p new_string
--output:--
"105;105; DROP TABLE Suppliers"
I can't find any documentation for backreferences to ruby's global variables, so congratulations you are a ruby pioneer.
impossible to replace the character with gsub
Replace your code with this:
def replace_chars(name)
chars = {
"̤" => "ç",
"Ì©" => "é",
"•" => "ï",
"â„¢" => "ô",
"Ž" => 'é',
"‘" => "ë",
"Â" => "ç"
}
puts "before #{name}"
chars.each do |key,value|
name.gsub!(key,value)
end
puts "after #{name}"
end
replace_chars('̤liver Žponime')
before ̤liver Žponime
after çliver éponime
`string.replace` doesn’t change the variable
According to the Javascript standard, String.replace
isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.
You can always just set the string to the modified value:
variableABC = variableABC.replace('B', 'D')
Edit: The code given above is to only replace the first occurrence.
To replace all occurrences, you could do:
variableABC = variableABC.replace(/B/g, "D");
To replace all occurrences and ignore casing
variableABC = variableABC.replace(/B/gi, "D");
How can I replace new lines with \n character
> s = "hi\nthere"
> puts s
hi
there
> puts s.gsub(/\n/, "\\n")
hi\nthere
Ruby Regex Replace Last Occurence of Grouping
If I correctly understood, you are interested in gsub
with codeblock
:
str.gsub(PATTERN) { |mtch|
puts mtch # the whole match
puts $~[3] # the third group
mtch.gsub($~[3], 'NEW') # the result
}
'abc'.gsub(/(b)(c)/) { |m| m.gsub($~[2], 'd') }
#⇒ "abd"
Probably you should handle the case when there are no 40
-s occureneces at all, like:
gsub($~[1], "NEW$~[1]") if $~[3].nil?
To handle all the possible cases, one might declare the group for Foo
:
# NOTE THE GROUP ⇓⇓⇓⇓⇓
▶ re = /(([1-3,5-9][0-9]|([4][0-9]))[a-z])*(Foo)/
#⇒ /(([1-3,5-9][0-9]|([4][0-9]))[a-z])*(Foo)/
▶ inp.gsub(re) do |mtch|
▷ $~[3].nil? ? mtch.gsub($~[4], "NEW#{$~[4]}") : mtch.gsub(/#{$~[3]}/, 'NEW')
▷ end
#⇒ "12a23b34cNEWd56eFoo\n12a45b34cNEWd89eFoo\nNEWaFoo\nNEWFoo\n12a23bNEWFoo"
Hope it helps.
Related Topics
Converting from Xml Name-Values into Simple Hash
Net::Ssh Sudo Command Hangs After Entering Password
Regex, How to Match Multiple Lines
How Is Each_With_Object Supposed to Work
Ruby - Digest::Digest Is Deprecated; Use Digest
Rails 3 Install Error: "Invalid Value for @Cert_Chain"
How to Create a Hash in Ruby That Compares Strings, Ignoring Case
To_Specs': Could Not Find Chef (>= 0) Amongst [] (Gem::Loaderror)
Calling Sinatra from Within Sinatra
Ruby Minitest: Suite- or Class- Level Setup
Detect If Application Was Started as Http Server or Not (Rake Task, Rconsole etc)
Ruby Hash Autovivification (Facets)
Windows/Ruby/Rails Install --- .Cannot Load Such File -- SQLite3/Sqlite3_Native Windows