In the example above, I have a String? value of dictionary key containing unescaped backslashes. The assertion fails because the literal string I defined for comparison is escaped.
How do I define the string literal so it is unescaped in the comparison?
Or should I be escaping the dictionary value?
For example, in Perl I would define the string using single quotes or q().
I saw that there is some sort of RFC for a similar Swift solution, but what is the workaround?
Your comparison will work if you use only one method, not both of them: either escape the characters (but do not use #...#). OR if you use #...#, don't escape the characters.
I.e. for a string X4\\7, both of the following will pass the comparison correctly:
"X4\\\\7"
#"X4\\7"#
Related
I have an issue facing me on a string in Flutter, specifically in a URL that includes '$' char.
Is there any way to escape the dollar sign $?
var url = Uri.parse('https://olinda.bcb.gov.br/olinda/servico/Expectativas/versao/v1/odata/ExpectativaMercadoMensais?$top=100&$skip=0&$orderby=Data%20desc&$format=json&$select=Indicador,DataReferencia,Mediana,baseCalculo');
Dart has something called String Interpolation. Here's a snippet from the docs:
To put the value of an expression inside a string, use ${expression}. If the expression is an identifier, you can omit the {}.
Here are some examples of using string interpolation:
String
Result
'${3 + 2}'
'5'
'${"word".toUpperCase()}'
'WORD'
'$myObject'
The value of myObject.toString()
In your case, the URL string contains exactly the escape symbol $ to make a String interpolation. Dart thinks all words after the $ symbol are identifiers (variables, functions etc.) but it doesn't find them defined anywhere. To fix it just do what #jamesdlin suggested: Escape the $ symbols like \$ or prefix the string with r like below:
r'https://...Mensais?$top=100&$skip=0&$orderby=...'.
Use this instead
var url = Uri.parse( 'https://olinda.bcb.gov.br/olinda/servico/Expectativas/versao/v1/odata/ExpectativaMercadoMensais?\$top=100&\$skip=0&\$orderby=Data%20desc&\$format=json&\$select=Indicador,DataReferencia,Mediana,baseCalculo');
Use a reverse slash to escape string
The following match returns false. How can I change the regular expression to correct it?
"hello$world" -match '^hello$(wo|ab).*$'
"hello$abcde" -match '^hello$(wo|ab).*$'
'hello$world' -match '^hello\$(wo|ab).*$'
'hello$abcde' -match '^hello\$(wo|ab).*$'
You need to quote the left hand side with single quotes so $world isn't treated like variable interpolation. You need to escape the $ in the right hand side so it isn't treated as end of line.
From About Quoting Rules:
When you enclose a string in double quotation marks (a double-quoted string), variable names that are preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing.
...
When you enclose a string in single-quotation marks (a single-quoted string), the string is passed to the command exactly as you type it. No substitution is performed.
From About Regular Expressions:
The two commonly used anchors are ^ and $. The carat ^ matches the start of a string, and $, which matches the end of a string. This allows you to match your text at a specific position while also discarding unwanted characters.
...
Escaping characters
The backslash \ is used to escape characters so they are not parsed by the regular expression engine.
The following characters are reserved: []().\^$|?*+{}.
You will need to escape these characters in your patterns to match them in your input strings.
Under what circumstances must one use quotes in a YAML file, specifically when using docker-compose.
For instance,
service:
image: "my-registry/repo:tag1"
environment:
ENV1: abc
ENV2: "abc"
ENV3: "a b c"
If spaces are required, for example, must one use quotes around the environment variable, as depicted in ENV3?
After some googling I've found a blog post
that touches this problem as I understood it.
I'll cite the most important part here:
plain scalars:
- a string
- a string with a \ backslash that doesn't need to be escaped
- can also use " quotes ' and $ a % lot /&?+ of other {} [] stuff
single quoted:
- '& starts with a special character, needs quotes'
- 'this \ backslash also does not need to be escaped'
- 'just like the " double quote'
- 'to express one single quote, use '' two of them'
double quoted:
- "here we can use predefined escape sequences like \t \n \b"
- "or generic escape sequences \x0b \u0041 \U00000041"
- "the double quote \" needs to be escaped"
- "just like the \\ backslash"
- "the single quote ' and other characters must not be escaped"
literal block scalar: |
a multiline text
line 2
line 3
folded block scalar: >
a long line split into
several short
lines for readability
Also I have not seen such docker-compose syntax to set env variables. Documentation suggests using simple values like
environment:
- ENV1=abc
- "ENV2=abc"
Where quotes " or ' are optional in this particular example according to what I've said earlier.
To see how to include spaces in env variables you can check out this so answer
Whether or not you need quotes, depends on the parser. Docker-compose AFAIK is still relying on the PyYAML module and that implements most of YAML 1.1 and has a few quirks of its own.
In general you only need to quote what could otherwise be misinterpreted or clash with some YAML construct that is not a scalar string. You also need (double) quotes for things that cannot be represented in plain scalars, single quoted scalars or block style literal or folded scalars.
Misinterpretation
You need to quote strings that look like some of the other data structures:
booleans: "True", "False", but PyYAML also assumes alternatives words like "Yes", "No", "On", "Off" represent boolean values ( and the all lowercase, all uppercase versions should be considered as well). Please note that the YAML 1.2 standard removed references to these alternatives.
integers: this includes string consisting of numbers only. But also hex (0x123) and octal number (0123). The octals in YAML 1.2 are written as 0o123, but PyYAML doesn't support this, however it is best to quote both.
A special integer that PyYAML still supports but again not in the YAML 1.2 specification are sexagesimals: base 60 number separated by colon (:), time indications, but also MAC addresses can be interpreted as such if the values between/after the colons are in the range 00-59
floats: strings like 1E3 (with optional sign ans mantissa) should be quoted. Of course 3.14 needs to be quoted as well if it is a string. And sexagesimal floats (with a mantissa after the number after the final colon) should be quoted as well.
timestamps: 2001-12-15T02:59:43.1Z but also iso-8601 like strings should be quoted to prevent them from being interpreted as timestamps
The null value is written as the empty string, as ~ or Null (in all casing types), so any strings matching those need to be quoted.
Quoting in the above can be done with either single or double quotes, or block style literal or folded scalars can be used. Please note that for the block-style you should use |- resp. >- in order not to introduce a trailing newline that is not in the original string.
Clashes
YAML assigns special meaning to certain characters or character combinations. Some of these only have special meaning at the beginning of a string, others only within a string.
characters fromt the set !&*?{[ normally indicate special YAML constructs. Some of these might be disambiguated depending on the following character, but I would not rely on that.
whitespace followed by # indicates an end of line comment
wherever a key is possible (and within block mode that is in many places) the combination of colon + space (:) indicates a value will be following. If that combination is part of your scalar string, you have to quote.
As with the misinterpretation you can use single or double quoting or block-style literal or folding scalars. There can be no end-of-line comments beyond the first line of a block-style scalar.
PyYAML can additionally get confused by any colon + space within a plain scalar (even when this is in a value) so always quote those.
Representing special characters
You can insert special characters or unicode code-points in a YAML file, but if you want these to be clearly visible in all cases, you might want to use escape sequences. In that case you have to use double quotes, this is the only mode that
allows backslash escapes. And e.g. \u2029. A full list of such escapes can be taken from the standard, but note that PyYAML doesn't implement e.g \/ (or at least did not when I forked that library).
One trick to find out what to quote or not is to use the library used to dump the strings that you have. My ruamel.yaml and PyYAML used by docker-compose, when potentially dumping a plain scalar, both try to read back (yes, by parsing the result) the plain scalar representation of a string and if that results in something different than a string, it is clear quotes need to be applied. You can do so too: when in doubt write a small program dumping the list of strings that you have using PyYAML's safe_dump() and apply quotes anywhere that PyYAML does.
I want replace a Letter with a literal $. I tried:
var s = string.replaceAll("Register","$10")
I want that this text Register saved to be changed to: $10 saved
Illegal group reference is the error I get.
If you look at the scaladoc for replaceAll, you'll see that it takes a regular expression string as the parameter. Escape the $ with a \, or use replaceAllLiterally
replaceAll uses a regular expressions to find the match. In the replacement string $ is a special character that refers to a specific capture group in the matching string. You have no capture groups so this is an error. It's not what you want anyway since you want the literal text "$10".
Usereplaceinstead ofreplaceAll`. It just does a direct string replacement.
This does not work:
scala> """one\r\ntwo\r\nthree\r\nfour""".replace("\r\n", "\n")
res1: String = one\r\ntwo\r\nthree\r\nfour
How to do that in Scala?
Is there a more idiomatic way of doing that, instead of using replace?
The problem is that """ quotes does not expand escape sequences. Three different approaches:
Use single " quotes in order to treat escape sequences correctly: "one\r\ntwo";
Use the s string interpolator, be careful following this approach cause this could lead to unexpected replacements: s"""one\r\ntwo""";
Call treatEscapes directly to expands escape sequences in your string: StringContext.treatEscapes("""one\r\ntwo""").
Refer also to this earlier question.
try this
"""one\r\ntwo\r\nthree\r\nfour""".replace("\\r\\n", "\n")
\ is treated as escape charater within string, so you need to tell the compiler that its not a escape character but a string.