Golang trimPrefix from string "\" - string

I've seen that golang have the function func TrimPrefix(s, prefix string) string which returns s without the provided leading prefix string.
My problem is that I have a string which start with the character "\" (for example "\foo"). When I try to use TrimPrefix I getting an error.
golang code:
var s = "\foo"
s = strings.TrimPrefix(s, "\")
fmt.Print(s)
error:
./prog.go:10:32: newline in string
./prog.go:10:32: syntax error: unexpected newline, expecting comma or )
I have seen that it is due to golang understang "\" as the scape character. Do you know if ther is any golang option I can use in order to make golang understand that I don't want to use "\" as the escape character?

"\" is not a valid Go string literal. What you get is a compile-time error. In interpreted string literals backslash \ is a special character.
If you want the string to contain a backslash character, you have to use the sequence \\:
var s = "\\foo"
s = strings.TrimPrefix(s, "\\")
Which will output (try it on the Go Playground):
foo
Another option is to use raw string literals where the backslash is not special:
var s = `\foo`
s = strings.TrimPrefix(s, `\`)
Try this one on the Go Playground.

if you only want to trim the prefix which is a specific prefix( like "\" is a prefix with length of 1 ), you can use slice function as :str[len(prefix):].
Just because it is a prefix -- head of a string and a length-known prefix.
Ignore my post if you only want to know the use of TrimPrefix. :D

Related

EOL error while concatinating strings when backslash(\) is used in python

Why doesn't it work? my gut feeling is it has something to do with the slashes(\);
savepath = ("C:\\Python\" + date4filename + ".txt")
Error is
File "C:\python\temp.py", line 2
savepath=("C:\\Python\" + date4filename)
^
SyntaxError: EOL while scanning string literal
[Finished in 0.191s]
Back slash has special meaning which is used to take away special meaning of special characters when prefixed, here it is double quote ("). For this reason we have raw strings in python.
Raw strings are defined using r' ' . When raw strings are used all characters inside string are treated normal with no special meaning
Since backslash has special meaning, to use actual backslash we need to use (\\)
savepath = ("C:\\Python\\" + date4filename + ".txt")
Not to make it complex, use os.path library
import os.path
os.path.join("c://python/", date4filename, ".txt")
To avoid these path problems, you can absolutely use *nix style forwardslash(/) in python regardless of platform

regex with named capture fails in XRegExp but works fine on regex101.com [duplicate]

In the regex below, \s denotes a space character. I imagine the regex parser, is going through the string and sees \ and knows that the next character is special.
But this is not the case as double escapes are required.
Why is this?
var res = new RegExp('(\\s|^)' + foo).test(moo);
Is there a concrete example of how a single escape could be mis-interpreted as something else?
You are constructing the regular expression by passing a string to the RegExp constructor.
\ is an escape character in string literals.
The \ is consumed by the string literal parsing…
const foo = "foo";
const string = '(\s|^)' + foo;
console.log(string);
… so the data you pass to the RegEx compiler is a plain s and not \s.
You need to escape the \ to express the \ as data instead of being an escape character itself.
Inside the code where you're creating a string, the backslash is a javascript escape character first, which means the escape sequences like \t, \n, \", etc. will be translated into their javascript counterpart (tab, newline, quote, etc.), and that will be made a part of the string. Double-backslash represents a single backslash in the actual string itself, so if you want a backslash in the string, you escape that first.
So when you generate a string by saying var someString = '(\\s|^)', what you're really doing is creating an actual string with the value (\s|^).
The Regex needs a string representation of \s, which in JavaScript can be produced using the literal "\\s".
Here's a live example to illustrate why "\s" is not enough:
alert("One backslash: \s\nDouble backslashes: \\s");
Note how an extra \ before \s changes the output.
As has been said, inside a string literal, a backslash indicates an escape sequence, rather than a literal backslash character, but the RegExp constructor often needs literal backslash characters in the string passed to it, so the code should have \\s to represent a literal backslash, in most cases.
A problem is that double-escaping metacharacters is tedious. There is one way to pass a string to new RegExp without having to double escape them: use the String.raw template tag, an ES6 feature, which allows you to write a string that will be parsed by the interpreter verbatim, without any parsing of escape sequences. For example:
console.log('\\'.length); // length 1: an escaped backslash
console.log(`\\`.length); // length 1: an escaped backslash
console.log(String.raw`\\`.length); // length 2: no escaping in String.raw!
So, if you wish to keep your code readable, and you have many backslashes, you may use String.raw to type only one backslash, when the pattern requires a backslash:
const sentence = 'foo bar baz';
const regex = new RegExp(String.raw`\bfoo\sbar\sbaz\b`);
console.log(regex.test(sentence));
But there's a better option. Generally, there's not much good reason to use new RegExp unless you need to dynamically create a regular expression from existing variables. Otherwise, you should use regex literals instead, which do not require double-escaping of metacharacters, and do not require writing out String.raw to keep the pattern readable:
const sentence = 'foo bar baz';
const regex = /\bfoo\sbar\sbaz\b/;
console.log(regex.test(sentence));
Best to only use new RegExp when the pattern must be created on-the-fly, like in the following snippet:
const sentence = 'foo bar baz';
const wordToFind = 'foo'; // from user input
const regex = new RegExp(String.raw`\b${wordToFind}\b`);
console.log(regex.test(sentence));
\ is used in Strings to escape special characters. If you want a backslash in your string (e.g. for the \ in \s) you have to escape it via a backslash. So \ becomes \\ .
EDIT: Even had to do it here, because \\ in my answer turned to \.

Add 'r' prefix to a python variable

I have string variable which is
temp = '1\2\3\4'
I would like to add a prefix 'r' to the string variable and get
r'1\2\3\4'
so that I can split the string based on '\'. I tried the following:
r'temp'
'r' + temp
r + temp
But none of the above works. Is there a simple to do it? I'm using python 3. I also tried to encode the string, using
temp.encode('string-escape')
But it returns the following error
LookupError: unknown encoding: string-escape
r is a prefix for string literals. This means, r"1\2\3\4" will not interpret \ as an escape when creating the string value, but keep \ as an actual character in the string. Thus, r"1\2\3\4" will have seven characters.
You already have the string value: there is nothing to interpret. You cannot have the r prefix affect a variable, only a literal.
Your temp = "1\2\3\4" will interpret backslashes as escapes, create the string '1\x02\x03\x04' (a four-character string), then assign this string to the variable temp. There is no way to retroactively reinterpret the original literal.
EDIT: In view of the more recent comments, you do not seem to, in fact, have a string "1\2\3\4". If you have a valid path, you can split it using
path.split(r'\')
or
path.split('\\')
but you probably also don't need that; rather, you may want to split a path into directory and file name, which is best done by os.path functions.
Wouldn't it just be re.escape(temp)?
Take for example the use case of trying to generate a pattern on the fly involving word boundaries. Then you can do this
r'\b' + re.escape(temp) + r'\b'
just to prefix r in variable in search, Please do this r+""+temp.
e.g.-
import re
email_address = 'Please contact us at: support#datacamp.com'
searchString = "([\w\.-]+)#([\w\.-]+)"
re.serach(r""+searchString, email_address)

In Swift how to obtain the "invisible" escape characters in a string variable into another variable

In Swift I can create a String variable such as this:
let s = "Hello\nMy name is Jack!"
And if I use s, the output will be:
Hello
My name is Jack!
(because the \n is a linefeed)
But what if I want to programmatically obtain the raw characters in the s variable? As in if I want to actually do something like:
let sRaw = s.raw
I made the .raw up, but something like this. So that the literal value of sRaw would be:
Hello\nMy name is Jack!
and it would literally print the string, complete with literal "\n"
Thank you!
The newline is the "raw character" contained in the string.
How exactly you formed the string (in this case from a string literal with an escape sequence in source code) is not retained (it is only available in the source code, but not preserved in the resulting program). It would look exactly the same if you read it from a file, a database, the concatenation of multiple literals, a multi-line literal, a numeric escape sequence, etc.
If you want to print newline as \n you have to convert it back (by doing text replacement) -- but again, you don't know if the string was really created from such a literal.
You can do this with escaped characters such as \n:
let secondaryString = "really"
let s = "Hello\nMy name is \(secondaryString) Jack!"
let find = Character("\n")
let r = String(s.characters.split(find).joinWithSeparator(["\\","n"]))
print(r) // -> "Hello\nMy name is really Jack!"
However, once the string s is generated the \(secondaryString) has already been interpolated to "really" and there is no trace of it other than the replaced word. I suppose if you already know the interpolated string you could search for it and replace it with "\\(secondaryString)" to get the result you want. Otherwise it's gone.

Replace a char with double qoute

I am constructing json code syntax in a string. The format needs to be {"field":"somedata"} and so on. The problem is that I need to use a string and the code that I wrote is:
astring=astring + "{\"field\":\"somedata\"}"
The problem is that when I save the string as a textfile the backslashes is also saved and disqualifies this as json.
The I tried to use a diff char (a dog) as a replacement for \" and tried to replace the dog using:
res_str=res_str.stringByReplacingOccurrencesOfString("🐶", withString: "\"")
But the backslash was included. And finally I tried to
res_str=res_str.stringByReplacingOccurrencesOfString("🐶", withString: String(UnicodeScalar(34)))
But the backslash is included. In PHP for example I could have used single quote as outer string separator but that isn't allowed in Swift.
Any ideas?

Resources