Replacing with regular expressions
Now, you've mastered matching with backreferences, you'll build up to replacing with backreferences, but first let's review str_replace() now that you've got regular expressions under your belt.
Remember str_replace() takes three arguments, string a vector of strings to do the replacements in, pattern that identifies the parts of strings to replace and replacement the thing to use as a replacement.
replacement can be a vector, the same length as string, each element specifies the replacement to be used in each string. Let's practice by anonymizing some of the contact objects you've seen so far.
이 연습은 강의의 일부입니다
String Manipulation with stringr in R
연습 안내
Text containing phone numbers has been pre-defined in a variable named contact.
- Replace a digit in
contactwith"X"usingstr_replace(). - Replace all digits in
contactwith"X"usingstr_replace_all(). (str_replace()will only replace the first match to thepattern.str_replace_all()will replace all matches to the pattern.) - Replace all digits in
contactusingstr_replace_all(), but now specify the vectorc("X", ".", "*", "_")asreplacement. Notice how now each string uses a different replacement character.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# View text containing phone numbers
contact
# Replace digits with "X"
str_replace(contact, DGT, ___)
# Replace all digits with "X"
str_replace_all(contact, DGT, ___)
# Replace all digits with different symbol
str_replace_all(contact, DGT, ___)