Hi, I think there is a bug in the way gsub() finds the end of line.
x <- " this is \n some test\n text "
#I want to remove all leading spaces at the beginning of lines
 "this is \n some test\n text "
I get the same result with gsub("^\\s+", "",x, perl=TRUE)
gsub correctly replaced the first occurrence, but it seems it has not correctly recognized the newline character so that the next occurrences are not substituded properly.
The expected output is:
"this is \nsome test\ntext "
Similarly if I try to remove all the white spaces till the end of the line:
 " this is \n some test\n text"
whereas I would have expected:
" this is\n some test\n text"
Note I have also tried using stringr::str_replace_all() but the results are the same.
This is because the circumflex "^" is an anchor to the beginning of the whole string, not to any position after a newline.
I think the mixed use of the words "line" and "string" in the standard reflects the fact that pattern matching is often performed one line at a time, i.e. after multiline input has been split into separate strings at line breaks.
The fine Regex Tutorial at http://www.regular-expressions.info/anchors.html states that some tools do treat the "^" as an anchor to the start of each line in the input.
You could try the following substitution (lookbehind requires perl=TRUE):
gsub("^\\s+|(?<=\n)\\s+", "", x, perl=TRUE)