← Back to R Course | Chapter 6: Strings | Lesson 5 of 7

gsub और sub

sub और gsub text में एक pattern ढूंढते हैं और इसे किसी दूसरी चीज़ से swap करते हैं, एक document में Find और Replace की तरह। sub सिर्फ पहला बदलता है, जबकि gsub सबको बदलता है।

In this page:

  1. gsub और sub
Syntax
r
sub(pattern, replacement, x)
gsub(pattern, replacement, x)

gsub और sub

sub(pattern, replacement, x) एक string में एक pattern का पहला match replace करता है, जबकि gsub() हर match replace करता है (g global के लिए है)।

दोनों default से regular expressions support करते हैं, इन्हें pattern-based text transformation के लिए powerful बनाते हुए। यह sed के single और global replace modes के बीच relationship mirror करता है।

Note: sub()/gsub() में fixed = TRUE इस्तेमाल करें जब आपका pattern एक literal string हो, regex नहीं, special-character surprises से बचने के लिए।

उदाहरण: gsub and sub

markup
text <- "cat bat cat sat"

cat(sub("cat", "dog", text), "\n")
cat(gsub("cat", "dog", text), "\n")
cat(gsub("[aeiou]", "*", text), "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. sub इस्तेमाल करना और हर match बदलने की उम्मीद करना, जब यह सिर्फ पहला replace करता है; gsub इस्तेमाल करें।
  2. pattern में . या + को plain characters की तरह इस्तेमाल करना, जब वे regex symbols हैं; fixed = TRUE इस्तेमाल करें या \\. से escape करें।
  3. argument order swap करना, जब pattern पहले आता है, फिर replacement और फिर text।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.