I would like to do something like this:
function say(name, age)
println("$name is $age!")
end
But this gives me an error because Julia thinks age! is the name of the variable. If I add a space between $age and ! then the printed string has a space between age and !, which I don't want. I tried \! which I saw elsewhere but my current Julia version gives me invalid escape sequence error.
Just add brackets
println("$name is $(age)!")
The accepted answer is great, but just in case you want other ways to do it, here are two more ways (though not using string interpolation as in your question):
function say1(name, age)
println(name, " is ", age, "!")
end
function say2(name, age)
println(string(name, " is ", age, "!"))
end
say1("Tom", 32)
## Tom is 32!
say2("Tom", 32)
## Tom is 32!
Related
I have a data frame in R. I have this working splendidly at the moment as a test of my initial regex. For reference, I have dplyr and magrittr installed, largely for other reasons, and I am following some project-wide conventions as far as whitespace and closing parentheses are concerned:
frame %<>% mutate(
columnA = case_when(
grepl("WXYZ *[1-9]{1,2}", columnB) == TRUE ~'HOORAY'
)
)
The thing is, I would like to replace 'HOORAY' with whatever grepl actually found. Right now, I am of course searching for strings containing WXYZ followed by any number of spaces (0 included) and then a single- or double-digit integer.
If, for example, grepl found the string "WXYZ 22", I want the corresponding entry in columnA to be written as "WXYZ 22". But then if it finds "WXYZ5" later, I want it to write "WXYZ5" in its own corresponding entry.
I want, in pseudocode TRUE ~ <what grepl found>.
Can I do this with case_when? If so, is there a better way?
If the case_when structure is necessary, this solution using stringr works:
grepl("WXYZ *[1-9]{1,2}", columnB) ~ str_extract(columnB, "WXYZ *[1-9]{1,2}")
Depending on what the bigger problem setup looks like, you could also just do:
mutate(columnA = str_extract(columnB, "WXYZ *[1-9]{1,2}"))
Note that columnA would be NA for situations where it fails to match. Also note that while grep expects the pattern first and then the target string, stringr functions expect the opposite.
Is that possible to use a pattern like this (see below) in grepl()?
(poverty OR poor) AND (eradicat OR end OR reduc OR alleviat) AND extreme
The goal is to determine if a sentence meets the pattern using
ifelse(grepl(pattern, x, ignore.case = TRUE),"Yes","No")
For example, if x = "end extreme poverty in the country", it will return "Yes", while if x = "end poverty in the country", it will return "No".
An earlier post here works only for single work like poor AND eradicat AND extreme, but not work for my case. Any way to achieve my goal?
Tried this, pattern = "(?=.*poverty|poor)(?=.*eradicat|end|reduce|alleviate)(?=.*extreme)", but it does not work. The error is 'Invalid regexp'
For using all 3 assertions, you can group the words using a non capture group.
^(?=.*(?:poverty|poor))(?=.*extreme)(?=.*(?:eradicat|end|reduc|alleviat)).+
^ Start of string
(?=.*(?:poverty|poor)) Assert either poverty OR poor
(?=.*extreme) Assert extreme
(?=.*(?:eradicat|end|reduc|alleviat)) Assert either eradicat OR end OR reduc or alleviat
.+ Match the whole line for example
Regex demo
For grepl, you have to use perl=T enabling PCRE for the lookarounds.
grepl('^(?=.*(?:poverty|poor))(?=.*extreme)(?=.*(?:eradicat|end|reduc|alleviat)).+', v, perl=T)
I need to insert a data frame into a SQL database. I've build the script (using loops, str_c, RODBC) to transform my data frame into a SQL Insert command, but I've run into the problem with a single "'" breaking the SQL.
Here is an example of the problem:
The Data Frame looks like this:
pk b
1 o'keefe
The desired SQL output is: INSERT INTO table (pk, b) (1, 'o\'keefe')
gsub("'", "\'", str_replace_na(df$b[1], ""))
[1] "o'keefe"
gsub("'", "\\\\'", str_replace_na(df$b[1], ""))
[1] "o\\'keefe"
I've tried str_replace, str_replace_all, gsub w/ fixed = TRUE and perl = TRUE and I get the same result.
I am aware of the comment on How to give Backslash as replacement in R string replace, which states cat() shows the slash. But this doesn't carry over to my data frame or SQL query.
Any help on this problem would be greatly appreciated!
Additional note, I am aware the R prints a double backslash as referenced http://r.789695.n4.nabble.com/gsub-replacing-double-backslashes-with-single-backslash-td4453328.html and R: How to replace space (' ') in string with a *single* backslash and space ('\ ') even though only one slash really exists. However, my SQL statement still won't work when zero or two backslashes are present.
"o\\'keefe" is in fact what you want: the double blackslash is in fact a representation of a single backslash.
For instance:
\U005C is the unicode character for the backslash. Yet:
"\U005C"
[1] "\\"
While \U002F is the unicode character for the forward slash and:
"\U002F"
[1] "/"
So your second solution already gave you what you want. Removing the unnecessary str_replace_na():
gsub("'", "\\\\'", df$b[1])
[1] "o\\'keefe"
Note: credit in fact goes to #Rui Barradas who showed that the double backslash represents a single backslash with:
nchar("\\")
[1] 1
Try putting the single quote inside ['].
x <- "o'keefe"
y <- gsub("[']", "\\\\'", s)
y
#[1] "o\\'keefe"
This seems to have added two characters to the string but no, there is just one \.
nchar(x)
#[1] 7
nchar(y)
#[1] 8
So this is a short example of a dataframe:
x<- c("WB (16)","CT (14)WB (15)","ET (13)CITG-TILm (16)EE-SS (17)TN-SE (17)")
My question is how to get sub(".*?)", "", x)(or a different function) to work such that this will be the result:
x<-c("WB (16)","WB (15)","TN-SE(17)")
instead of
x<-c("","WB (15)")
I got different types of letters (so not only WB, CT and TN-SE),such as:
"NBIO(15)" "CITG-TP(08)" "BK-AR(10)"
So it should be a general function...
Thanks!
Could you please try following.
sub(".*[0-9]+[^)]\\)?([^)$])", "\\1", x)
Output will be as follows.
[1] "WB (16)" "WB (15)" "TN-SE (17)"
Where Input will be as follows.
> x
[1] "WB (16)" "CT (14)WB (15)"
[3] "ET (13)CITG-TILm (16)EE-SS (17)TN-SE (17)"
Explanation: Following is only for explanation purposes.
sub(" ##Using sub function of Base R here.
##sub works on method of sub(regex_to_match_current_line's_stuff, new_string/variable/value out of matched,regex, variable)
.*[0-9]+[^)]\\) ##Using look ahead method of regex by mentioning .*(everything till) a ) is NOT found then mentioning ) there to cover it too so it will match till a ) which is NOt on end of line.
? ##? this makes sure above regex is matched first and it will move for next regex condition as per look ahead functoianlity.
([^)$])", ##() means in R to put a value into R's memory to remember it kind of place holder in memory, I am mentioning here to keep everything till a ) found at last.
"\\1", ##Substitute whole line with \\1 means first place holder's value.
x) ##Mentioning variable/vector's name here.
I think that I understand what you want. This certainly works on your example.
sub(".*?([^()]+\\(\\d+\\))$", "\\1", x)
[1] "WB (16)" "WB (15)" "TN-SE (17)"
Details: This looks for something of the form SomeStuff (Numbers) at the end of the string and throws away anything before it. SomeStuff is not allowed to contain parentheses.
I have what is probably a really dumb grep in R question. Apologies, because this seems like it should be so easy - I'm obviously just missing something.
I have a vector of strings, let's call it alice. Some of alice is printed out below:
T.8EFF.SP.OT1.D5.VSVOVA#4
T.8EFF.SP.OT1.D6.LISOVA#1
T.8EFF.SP.OT1.D6.LISOVA#2
T.8EFF.SP.OT1.D6.LISOVA#3
T.8EFF.SP.OT1.D6.VSVOVA#4
T.8EFF.SP.OT1.D8.VSVOVA#3
T.8EFF.SP.OT1.D8.VSVOVA#4
T.8MEM.SP#1
T.8MEM.SP#3
T.8MEM.SP.OT1.D106.VSVOVA#2
T.8MEM.SP.OT1.D45.LISOVA#1
T.8MEM.SP.OT1.D45.LISOVA#3
I'd like grep to give me the number after the D that appears in some of these strings, conditional on the string containing "LIS" and an empty string or something otherwise.
I was hoping that grep would return me the value of a capturing group rather than the whole string. Here's my R-flavoured regexp:
pattern <- (?<=\\.D)([0-9]+)(?=.LIS)
nothing too complicated. But in order to get what I'm after, rather than just using grep(pattern, alice, value = TRUE, perl = TRUE) I'm doing the following, which seems bad:
reg.out <- regexpr(
"(?<=\\.D)[0-9]+(?=.LIS)",
alice,
perl=TRUE
)
substr(alice,reg.out,reg.out + attr(reg.out,"match.length")-1)
Looking at it now it doesn't seem too ugly, but the amount of messing about it's taken to get this utterly trivial thing working has been embarrassing. Anyone any pointers about how to go about this properly?
Bonus marks for pointing me to a webpage that explains the difference between whatever I access with $,# and attr.
Try the stringr package:
library(stringr)
str_match(alice, ".*\\.D([0-9]+)\\.LIS.*")[, 2]
You can do something like this:
pat <- ".*\\.D([0-9]+)\\.LIS.*"
sub(pat, "\\1", alice)
If you only want the subset of alice where your pattern matches, try this:
pat <- ".*\\.D([0-9]+)\\.LIS.*"
sub(pat, "\\1", alice[grepl(pat, alice)])