Question

Is it possible to insert a non-character, in this case -, if a particular criteria is met?

For example: If there are five numeric characters (12345), then insert a - after the 2nd numeric character (12-345).

I am trying to fix street addresses.

Thanks!

Was it helpful?

Solution

s = "abc 12345 def"
sub("([0-9]{2})([0-9]{3})", "\\1-\\2", s)
# "abc 12-345 def"

This will find first instance of 5 numbers in a row and add a "-" after the second number. See http://stat.ethz.ch/R-manual/R-patched/library/base/html/regex.html for R regex syntax.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top