Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all occurrences of a pattern in a string

Tags:

r

character

Used to run R with numbers and matrix, when it comes to play with strings and characters I am lost. I want to analyze some data where the time is read into R as follow:

>my.time.char[1]
[1] "\"2011-10-05 15:55:00\"" 

I want to end up with a string containing only:

"2011-10-05 15:55:00"

Using the function sub() (that i barely understand...), I got the following result:

> sub("(\")","",my.time.char[1])
[1] "2011-10-05 15:55:00\""

This is closer to the format i am looking for, but I still need to get rid of the two last characters (\").

like image 798
Simon Avatar asked May 12 '12 02:05

Simon


People also ask

How do you replace all occurrences of a regex pattern in a string?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.

What we should use if we want to replace all matching occurrences of a pattern use?

Given a string and a pattern, replace multiple occurrences of a pattern by character 'X'. The conversion should be in-place and the solution should replace multiple consecutive (and non-overlapping) occurrences of a pattern by a single 'X'.

Does replace replace all occurrences?

The replaceAll() method will substitute all instances of the string or regular expression pattern you specify, whereas the replace() method will replace only the first occurrence.

How do you replace all occurrences of a string in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.


1 Answers

The second line from ?sub explains:

sub and gsub perform replacement of the first and all matches respectively.

which should tell you to use gsub instead.

like image 53
joran Avatar answered Sep 27 '22 21:09

joran