I want to replace all occurrences of a single quote ( ') with a single backslash quote ( \'). I tried to do this with gsub, but I get a partial duplication of strings:
'
\'
gsub
a = "abc 'def' ghi" a.gsub("'", "\\'") # => "abc def' ghidef ghi ghi"
Can someone explain why this is happening and what is the solution for this?
This is because it "\\'"is of particular importance when it occurs as an argument for substitution gsub, namely, it means a substring after the match.
"\\'"
To do what you want, you can use a block:
a.gsub("'"){"\\'"} # => "abc \\'def\\' ghi"
, , \\.
\\
"\\'" \' - , . \' Ruby regex , , . , .
abc 'def' ghi ^
, '. , .. def' ghi.
def' ghi
abc def' ghidef' ghi ++++++++
:
abc def' ghidef' ghi ^
' , .. ghi.
ghi
abc def' ghidef ghi ghi ++++
, :
a.gsub(/'/, "\\\\'" )
abc\'def \' ghi
Source: https://habr.com/ru/post/1625430/More articles:Make part of the name matplotlib bold and a different color - pythonHorrible Windows Server 2012 R2 and Visual Studio Crash - c #встроенный метод пространства имен для управления конкретным кодом платформы в С++ - c++Swift protocol compliance: candidate has inconsistent type - iosInstalling the OAuth PECL Package on PHP 5 on OS X - phpIs it possible to change html content without using JavaScript? - javascriptIs there a way to dynamically change content without javascript? - htmlProblem with Android Studio during installation - androidError logging into Heroku from the command line - ruby-on-railstemplate typedef includes char [] [] - works with VS2008, but not gcc - c ++All Articles