Ruby Filter gsub replace \\n - ruby

I want to replace '\\n' with '\n'
i am using the gsub method but cannot replace
ruby
{
code => "#mystring=event.get('stockLines');
#mystring=#mystring.gsub('\\\n', '\n');"
}

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.
Read more
In your case:
#mystring.gsub("\\n", "\n")
The essential difference between the two literal forms of strings (single or double quotes) is that double quotes allow for escape sequences while single quotes do not!

Escaping of the backslash can be a bit weird.
For a regular Ruby script the code would be:
#mystring = event.get('stockLines').gsub('\\\\\n', '\n')
It seems like in logstash config the code is also in a string, so it needs to be escaped once more, i.e.:
ruby
{
code => "#mystring = event.get('stockLines').gsub('\\\\\\\\\\n', '\\n');"
}

Related

Replacing ' by \' in Ruby [duplicate]

s = "#main= 'quotes'
s.gsub "'", "\\'" # => "#main= quotes'quotes"
This seems to be wrong, I expect to get "#main= \\'quotes\\'"
when I don't use escape char, then it works as expected.
s.gsub "'", "*" # => "#main= *quotes*"
So there must be something to do with escaping.
Using ruby 1.9.2p290
I need to replace single quotes with back-slash and a quote.
Even more inconsistencies:
"\\'".length # => 2
"\\*".length # => 2
# As expected
"'".gsub("'", "\\*").length # => 2
"'a'".gsub("'", "\\*") # => "\\*a\\*" (length==5)
# WTF next:
"'".gsub("'", "\\'").length # => 0
# Doubling the content?
"'a'".gsub("'", "\\'") # => "a'a" (length==3)
What is going on here?
You're getting tripped up by the specialness of \' inside a regular expression replacement string:
\0, \1, \2, ... \9, \&, \`, \', \+
Substitutes the value matched by the nth grouped subexpression, or by the entire match, pre- or postmatch, or the highest group.
So when you say "\\'", the double \\ becomes just a single backslash and the result is \' but that means "The string to the right of the last successful match." If you want to replace single quotes with escaped single quotes, you need to escape more to get past the specialness of \':
s.gsub("'", "\\\\'")
Or avoid the toothpicks and use the block form:
s.gsub("'") { |m| '\\' + m }
You would run into similar issues if you were trying to escape backticks, a plus sign, or even a single digit.
The overall lesson here is to prefer the block form of gsub for anything but the most trivial of substitutions.
s = "#main = 'quotes'
s.gsub "'", "\\\\'"
Since \it's \\equivalent if you want to get a double backslash you have to put four of ones.
You need to escape the \ as well:
s.gsub "'", "\\\\'"
Outputs
"#main= \\'quotes\\'"
A good explanation found on an outside forum:
The key point to understand IMHO is that a backslash is special in
replacement strings. So, whenever one wants to have a literal
backslash in a replacement string one needs to escape it and hence
have [two] backslashes. Coincidentally a backslash is also special in a
string (even in a single quoted string). So you need two levels of
escaping, makes 2 * 2 = 4 backslashes on the screen for one literal
replacement backslash.
source

How to escape special chars powershell

I am using the code below to send some keys to automate some process in my company.
$wshell = New-Object -ComObject wscript.shell;
$wshell.SendKeys("here comes my string");
The problem is that the string that gets sent must be sanitazed to escape some special chars as described here.
For example: {, [, +, ~ all those symbols must be escaped like {{}, {[}, {+}, {~}
So I am wondering: is there any easy/clean way to do a replace in the string? I dont want to use tons of string.replace("{","{{}"); string.replace("[","{[}")
What is the right way to do this?
You can use a Regular Expression (RegEx for short) to do this. RegEx is used for pattern matching, and works great for what you need. Ironicly you will need to escape the characters for RegEx before defining the RegEx pattern, so we'll make an array of the special characters, escape them, join them all with | (which indicates OR), and then replace on that with the -replace operator.
$SendKeysSpecialChars = '{','}','[',']','~','+','^','%'
$ToEscape = ($SendKeysSpecialChars|%{[regex]::Escape($_)}) -join '|'
"I need to escape [ and } but not # or !, but I do need to for %" -replace "($ToEscape)",'{$1}'
That produces:
I need to escape {[} and {}} but not # or !, but I do need to for {%}
Just put the first two near the beginning of the script, then use the replace as needed. Or make a function that you can call that'll take care of the replace and the SendKeys call for you.
You can use Here Strings.
Note: Here Strings were designed for multi-line strings, but you can still use them to escape expression characters.
As stated on this website.
A here string is a single-quoted or double-quoted string which can
span multiple lines. Expressions in single-quoted strings are not
evaluated.
All the lines in a here-string are interpreted as strings,
even though they are not enclosed in quotation marks.
Example:
To declare a here string you have to use a new-line for the text
itself, Powershell syntax.
$string = #'
{ [ + ~ ! £ $ % ^ & ( ) _ - # ~ # '' ""
'#
Output: { [ + ~ ! £ $ % ^ & ( ) _ - # ~ # '' ""

Unexpected behavior with ruby gsub and '\\' [duplicate]

s = "#main= 'quotes'
s.gsub "'", "\\'" # => "#main= quotes'quotes"
This seems to be wrong, I expect to get "#main= \\'quotes\\'"
when I don't use escape char, then it works as expected.
s.gsub "'", "*" # => "#main= *quotes*"
So there must be something to do with escaping.
Using ruby 1.9.2p290
I need to replace single quotes with back-slash and a quote.
Even more inconsistencies:
"\\'".length # => 2
"\\*".length # => 2
# As expected
"'".gsub("'", "\\*").length # => 2
"'a'".gsub("'", "\\*") # => "\\*a\\*" (length==5)
# WTF next:
"'".gsub("'", "\\'").length # => 0
# Doubling the content?
"'a'".gsub("'", "\\'") # => "a'a" (length==3)
What is going on here?
You're getting tripped up by the specialness of \' inside a regular expression replacement string:
\0, \1, \2, ... \9, \&, \`, \', \+
Substitutes the value matched by the nth grouped subexpression, or by the entire match, pre- or postmatch, or the highest group.
So when you say "\\'", the double \\ becomes just a single backslash and the result is \' but that means "The string to the right of the last successful match." If you want to replace single quotes with escaped single quotes, you need to escape more to get past the specialness of \':
s.gsub("'", "\\\\'")
Or avoid the toothpicks and use the block form:
s.gsub("'") { |m| '\\' + m }
You would run into similar issues if you were trying to escape backticks, a plus sign, or even a single digit.
The overall lesson here is to prefer the block form of gsub for anything but the most trivial of substitutions.
s = "#main = 'quotes'
s.gsub "'", "\\\\'"
Since \it's \\equivalent if you want to get a double backslash you have to put four of ones.
You need to escape the \ as well:
s.gsub "'", "\\\\'"
Outputs
"#main= \\'quotes\\'"
A good explanation found on an outside forum:
The key point to understand IMHO is that a backslash is special in
replacement strings. So, whenever one wants to have a literal
backslash in a replacement string one needs to escape it and hence
have [two] backslashes. Coincidentally a backslash is also special in a
string (even in a single quoted string). So you need two levels of
escaping, makes 2 * 2 = 4 backslashes on the screen for one literal
replacement backslash.
source

Keep spaces with YAML

I have this in my YAML file:
test: I want spaces before this text
In my case I would like to have a space before the text in my array or json when converted. Is that possible? How?
With JSON as output it's parsed like this:
{
"test": "I want spaces before this text"
}
No spaces.
You can test it here
You would have to quote your scalar with either single or double quotes instead of using a plain scalar (i.e. one without quotes). Which one of those two is more easy to use depends on whether there are special characters in your text.
If you use single quotes:
test: ' I want spaces before this text'
this would require doubling any single quotes already existing in your text (something like ' abc''def ').
If you use double quotes:
test: " I want spaces before this text"
this would require backslash escaping any double quotes already existing in your text (something like " abc\"def ").
With \t this work
Example:
var options = {
\t hostname: 'localhost',
\t port: 4433
};

Regex for substituting backslash?

I have this:
a = "whut.\\nErgh"
What I want to achieve is:
"whut.\nErgh" #sub 2 backslashes with 1 backslash
I tried this:
a.gsub(/\\\\/) { '\\' }
but it still returns me two backslashes.
Could someone please explain what went wrong here?
There are not two backslashes in "whut.\\nErgh" but just one.
"\\" is just one backslash char, the first \ is used to escape the backslash in a string.
If you want to convert \\n to a newline char, then use:
"whut.\\nErgh".gsub(/\\n/, "\n")
Try this :
"whut.\\nErgh".gsub(/\\n/, "")

Resources