I am unsure why this doesn't work:
string.replaceAll('\\"','"')
I want to replace all \" with "
Any idea?
I have also tried
string.replaceAll("[\"]","\"")
The first argument to the replaceAll method is a regular expression, so the backslash character has significance there and needs to be escaped. You could use the forward-slash string delimiter to avoid double-escaping.
assert (/Hello, \"Joe\"/.replaceAll(/\\"/, '"') == 'Hello, "Joe"')
Related
Say I have a function that accepts a string and interpolates it inside quotes.
print_str() (
printf '"%s"\n' "$1"
)
Since the function encloses the input in double quotes, I want to escape all double quotes, if any, in the argument. But, critically, double quotes that are already escaped must be preceded by a backslash. In short, the function must add one layer of escaping to all double quotes in the argument, be that the first layer or an additional layer.
Examples:
'abc"def' -> 'abc\"def'
'{ "json": "{ \"key\": \"value\" }" }' -> '{ \"json\": \"{ \\\"key\\\": \\\"value\\\" }\" }'
The tricky part for me is determining whether a backslash preceding a double quote is actually escaping the double quote, because, for example, in '\\"' the backslash does not escape the double quote even though it immediately precedes the double quote.
I've thought about using sed and checking whether the number of backslashes before a double quote is odd or even, but that seems pretty convoluted. I managed to get the solution I wanted by piping the input through jq -R ., but I am wondering if there is another way to do it. In particular, I am looking for something that works in POSIX shell.
EDIT:
For further clarification, I am seeking some function that will add an additional layer of escaping to double quotes in a given string.
some_function() {
# IDK what the implementation would be
}
Then, some_function in conjunction with print_str would producing the following output.
string='{ "json": "{ \"key\": \"value\" }" }'
print_str "$(some_function "$string")"
# -> prints "{ \"json\": \"{ \\\"key\\\": \\\"value\\\" }\" }"
You don't need to count anything
sed 's/["\]/\\&/g; s/.*/"&"/'
Are there any "quote" symbols that you can use if you run out of them?
I know one can use " and ' (and, perhaps a combination of them) like "''" (somehow)
A example of a "additional" "quote" symbol would be
\" inside quotes.
If I make a python script, and "used up" both " and ', is there any more chars that I can use to indicate a quote?
No. From what I can tell, ' and " are the only quotes than can be used in a string literal. The Lexical Analysis page contains this information:
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings).
Which suggests that those are the only two options.
No, " and ' are the only quote characters in Python.
If you run out of quote symbols you can "escape" quotes with a backslash(\), which will ignore the quotes and just make them part of the string.
For example, this would be a valid string:
print("hello \"bob\"")
This would return 'hello "bob"'
No, their are no other quote chracters in Python for right now
As far as I know ' and " are tho only quote characters in python
but if you count a multi line string then it would look like this:
multiline = """
string
string
string
"""
and to make a list of them you would use:
multiline.splitlines()
How can I include quotes for string and characters as part of the string. Example is "This is a \" string" which should result in one string instead of "This is a \" as one string and string" as an error in this case. The same goes for the characters. Example is '\'', but
in my case it's only '\'.
This is my current solution which works only without quotes.
CHARACTER
: '\'' ~('\'')+ '\''
;
STRING
: '"' ~('"')+ '"'
;
Your string/char rules don't handle escape sequences correctly. For the character it should be:
CHARACTER: '\'' '\\'? '.' '\'';
Here we make the escape char (backshlash) be part of the rule and require an additional char (whatever it is) follow it. Similar for the string:
STRING: '"' ('\\'? .)+? '"';
By using +? we are telling ANTLR4 to match in a non-greedy manner, stopping at the first non-escaped quote char after the initial one.
In perl suppose I have a string like 'hello\tworld\n', and what I want is:
'hello world
'
That is, "hello", then a literal tab character, then "world", then a literal newline. Or equivalently, "hello\tworld\n" (note the double quotes).
In other words, is there a function for taking a string with escape sequences and returning an equivalent string with all the escape sequences interpolated? I don't want to interpolate variables or anything else, just escape sequences like \x, where x is a letter.
Sounds like a problem that someone else would have solved already. I've never used the module, but it looks useful:
use String::Escape qw(unbackslash);
my $s = unbackslash('hello\tworld\n');
You can do it with 'eval':
my $string = 'hello\tworld\n';
my $decoded_string = eval "\"$string\"";
Note that there are security issues tied to that approach if you don't have 100% control of the input string.
Edit: If you want to ONLY interpolate \x substitutions (and not the general case of 'anything Perl would interpolate in a quoted string') you could do this:
my $string = 'hello\tworld\n';
$string =~ s#([^\\A-Za-z_0-9])#\\$1#gs;
my $decoded_string = eval "\"$string\"";
That does almost the same thing as quotemeta - but exempts '\' characters from being escaped.
Edit2: This still isn't 100% safe because if the last character is a '\' - it will 'leak' past the end of the string though...
Personally, if I wanted to be 100% safe I would make a hash with the subs I specifically wanted and use a regex substitution instead of an eval:
my %sub_strings = (
'\n' => "\n",
'\t' => "\t",
'\r' => "\r",
);
$string =~ s/(\\n|\\t|\\n)/$sub_strings{$1}/gs;
Is there an easy way, using a subroutine maybe, to print a string in Perl without escaping every special character?
This is what I want to do:
print DELIMITER <I don't care what is here> DELIMITER
So obviously it will great if I can put a string as a delimiter instead of special characters.
perldoc perlop, under "Quote and Quote-like Operators", contains everything you need.
While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching
capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of
them. In the following table, a "{}" represents any pair of delimiters you choose.
Customary Generic Meaning Interpolates
'' q{} Literal no
"" qq{} Literal yes
`` qx{} Command yes*
qw{} Word list no
// m{} Pattern match yes*
qr{} Pattern yes*
s{}{} Substitution yes*
tr{}{} Transliteration no (but see below)
<<EOF here-doc yes*
* unless the delimiter is ''.
$str = q(this is a "string");
print $str;
if you mean quotes and apostrophes with 'special characters'
You can use the __DATA__ directive which will treat all of the following lines as a file that can be accessed from the DATA handle:
while (<DATA>) {
print # or do something else with the lines
}
__DATA__
#!/usr/bin/perl -w
use Some::Module;
....
or you can use a heredoc:
my $string = <<'END'; #single quotes prevent any interpolation
#!/usr/bin/perl -b
use Some::Module;
....
END
The printing is not doing special things to the escapes, double quoted strings are doing it. You may want to try single quoted strings:
print 'this is \n', "\n";
In a single quoted string the only characters that must be escaped are single quotes and a backslash that occurs immediately before the end of the string (i.e. 'foo\\').
It is important to note that interpolation does not work with single quoted strings, so
print 'foo is $foo', "\n";
Will not print the contents of $foo.
You can pretty much use any character you want with q or qq. For example:
#!/usr/bin/perl
use utf8;
use strict; use warnings;
print q∞This is a test∞;
print qq☼\nThis is another test\n☼;
print q»But, what is the point?»;
print qq\nYou are just making life hard on yourself!\n;
print qq¿That last one is tricky\n¿;
You cannot use qq DELIMITER foo DELIMITER. However, you could use heredocs for a similar effect:
print <<DELIMITER
...
DELIMETER
;
or
print <<'DELIMETER'
...
DELIMETER
;
but your source code would be really ugly.
If you want to print a string literally and you have Perl 5.10 or later then
say 'This is a string with "quotes"' ;
will print the string with a newline.. The importaning thing is to use single quotes ' ' rather than double ones " "