2

I am trying to add the time stamp after a 4-digit number (4 digits is year), I am currently using the following code:

 temp.table[,"admission_datetime"] <- gsub("/2010$", "/2010 0:00:00", temp.table[,"admission_datetime"])
 temp.table[,"admission_datetime"] <- gsub("/1976$", "/1976 0:00:00", temp.table[,"admission_datetime"])
 temp.table[,"admission_datetime"] <- gsub("/1990$", "/1990 0:00:00", temp.table[,"admission_datetime"])
 temp.table[,"admission_datetime"] <- gsub("/1978$", "/1978 0:00:00", temp.table[,"admission_datetime"])

The code works fine for me, but a bit clumsy and inflexible, I know I can use [0-9]{4} to capture the 1976,1978,1990,2010, but I don't know how to put them back using regex, can anyone enlighten me? Thanks.

2
  • Should be able to reference the previous capture using \1 Commented Mar 4, 2011 at 3:41
  • i searched a bit about backreferencing, i'm in a rush so i just skip it and use the old-dumb method, how can I use the \1 thingy? thanks! Commented Mar 4, 2011 at 3:42

3 Answers 3

4

This should work:

temp.table[,"admission_datetime"] <- gsub("/([0-9]{4})$", "/\\1 0:00:00", temp.table[,"admission_datetime"])
Sign up to request clarification or add additional context in comments.

Comments

1

If you enclose the pattern in parentheses, you can then refer to it in the replacement by using \1, \2, etc. depending on which expression you want to return:

gsub("/([0-9][0-9][0-9][0-9])$","\\1 0:00:00","1/21/1985")

More complicated variants are possible:

gsub("([0-9]+)/([0-9]+)/([0-9]+)","\\2/\\1/\\3 0:00:00","1/21/1985")

Comments

1

Try using either of these 3 awesome must-know websites that help with finding any REGEX desired:

http://gskinner.com/RegExr/

http://lumadis.be/regex/test_regex.php

http://cs.union.edu/~hannayd/csc350/simulators/RegExp/reg.htm

3 Comments

those are good references, but they don't pin point the issue I had a moment ago, I tried regular-expressions.info before I asked question, but there are too many things to read and I don't have enough time.
@Lokheart, I see your downvote, sorry for wasting your time. I just thought you might be interested and enthousiastic in knowing what you are actually doing and why it works like it does
Your information is nice, but no answer on the problem and hence not helpful at all. The problem is not the regex, the problem is how to reference the captured in R. And that's not on those websites.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.