Amarjeet
Amarjeet

Reputation: 925

How to delete the delimiter in a string only from a particular position?

I have the following text:

//@A:Good!//@B: Wow!//@C: How come?@D//@E:    
//@A:Good!//@B: Wow!//@C: How come?@D//

I want to delete only the // from this string if there is no @ associated with it.

The output I want is:

 //@A:Good!//@B: Wow!//@C: How come?@D//@E:    
 //@A:Good!//@B: Wow!//@C: How come?@D

Upvotes: 2

Views: 60

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can use a capturing group and replace with back-reference. This way, you do not even need to specify perl=T:

str <- '//@A:Good!//@B: Wow!//@C: How come?@D//@E: //@A:Good!//@B: Wow!//@C: How come?@D//'
gsub('//([^@]|$)', '\\1', str)

Explanation of the pattern:

  • // - 2 literal slashes
  • ([^@]|$) - capturing group 1 that matches a non-@ (with [^@]) or the end of string $.

  • \\1 - is the back-reference to the captured group contents to put it back into the replaced string.

Output of the demo program:

[1] "//@A:Good!//@B: Wow!//@C: How come?@D//@E: //@A:Good!//@B: Wow!//@C: How come?@D"

Upvotes: 2

vks
vks

Reputation: 67968

\\/\\/(?!@)

You can try this with gsub and perl=True.See demo.

https://regex101.com/r/mT0iE7/34

Upvotes: 0

anubhava
anubhava

Reputation: 784998

You can search using negative lookahead:

//(?!@)

and replace with empty string.

RegEx Demo

Upvotes: 3

Related Questions