R regexp for sharing text parts

I want to swap text parts from left to right and vice versa. This works fine from left to right:

sub("(^x+)(.+)", "\\2\\1","xxxxx6.0")
[1] "6.0xxxxx"

while in the other direction there is:

sub("(.+)(x+$)", "\\2\\1","6.0xxxxx")
[1] "x6.0xxxx"

What am I missing?

+4
source share
2 answers

The problem is your second regular expression. The second regular expression has .+, which is the greedy quantifier corresponding to each character. The first group will try to match as much as possible.

(6.0xxxx)(x)

In parentheses are two groups that will match your regular expression.

There are two ways to solve this problem. The first is to use a lazy quantifier instead of a greedy quantifier:

/(.+?)(x+$)/

+ , , .

(6.0)(xxxxx)

.

, , , x.

/(^[^x]+)(+x$)/

, ( , x). x 1, .

+4

lookbehind (?<!...) , , (.+) . lookbehind , (x+$) , x:

sub("(.+)(?<!x)(x+$)", "\\2\\1", "6.0xxxxx", perl=TRUE)
#[1] "xxxxx6.0"
+3
source

All Articles