R - Sub Text Using Regular Expressions

r, regex

Solution

You're already matching multiple times - that's what `gsub` does, whereas `sub` only matches once.

The problems are twofold. First, your regex is "greedy". This is the default, and means that anything like `.*` will match as much as possible instead of as little as possible. You can make it non-greedy, causing it to match only "(q + r) AS" and "(s + t) AS" instead of the whole thing. Then, since you're already using gsub, the match will automatically happen multiple times.

The second thing isn't actually a problem, it's just unnecessary. Your second string says `"\\1"`, that is, "replace with captured group number one". But, there is no capture group number one! Instead, just use an empty string.

That should give you:

sql<- gsub(" \\(.*?AS", "", sql)
"a, b, c, d"

Problem

@Greg Snow was kind enough to introduce me to pattern matching using regular expressions. I used his advice to perform the following: ``` sql <- "SELECT a, b, (q + r) AS c, (s + t) AS d FROM tbl WHERE x=y" sql <- gsub("^.*SELECT *(.*?) +FROM.*$", "\\1", sql) "a, b, (q + r) AS c, (s + t) AS d" ``` I was curious and tried to extend this logic to replace "anything after a comma up to and including 'AS': ``` sql<- gsub(" \\(.*AS", "\\1", sql) "a, b, d" ``` I wanted it to return "a, b, c, d". However, I see what going on - it's matching my pattern across the whole string starting with the comma after 'b' and ending it with the second AS, not the first. My question is, how can I match a pattern multiple times within the same string? I know I'm doing something wrong with the syntax.

Original source