0

I want to replace DM*13:01:01:02 with DM*13:01:01:01. However my script also changes DM*11:01:01:01, DM*03:01:01:01, DM*01:01:01:01 to DM*13:01:01:01. I do not want these to be changed

The script I use:

> papST$DM_c1 <-gsub("[DM*]\\d[13][:]\\d[01][:]\\d[01][:]\\d[02]", "*13:01:01:01", papST$DM_o1, perl = TRUE)
3
  • 2
    You should try entering your regex into a helper tool like regex101.com. Your regex contains a lot of things that don't make sense to me, especially if you are basically trying to match a single fixed string. Commented Jun 2, 2017 at 0:04
  • \\d means any digit. [xy] matches any character x or y. So \\d[13] matches 01,03,11,13,21,23.... and so on. Why not just gsub("DM*13:01:01:02", "DM*13:01:01:01", papST$DM_o1, fixed=TRUE) ? Commented Jun 2, 2017 at 0:05
  • Thank you, my problem was I tried to over complicate a relatively simple substitution. Commented Jun 2, 2017 at 0:37

1 Answer 1

1

Based on the examples you have given, you don't really need to use any fancy regex features to do the specific replacement you have mentioned. The only thing you need to include in your pattern is a backslash so that * doesn't get treated as a special character:

x = c("DM*13:01:01:02", "DM*11:01:01:01", "DM*03:01:01:01", "DM*01:01:01:01")
gsub("DM\\*13:01:01:02", "DM*13:01:01:01", x)

If there are more values that need replacing, like you want to replace all values ending in 02, then you may need to bring in some of the "pattern matching" features in regular expressions, but it's important not to overcomplicate things.

For reference, to replace all 02s at the end of your strings, you could use a simple regex that uses $, which matches at the end of a string:

gsub("02$", "01", x)
Sign up to request clarification or add additional context in comments.

1 Comment

Great a simple script works, I will remember this for the future. Thank you!

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.