gsub और sub
sub और gsub text में एक pattern ढूंढते हैं और इसे किसी दूसरी चीज़ से swap करते हैं, एक document में Find और Replace की तरह। sub सिर्फ पहला बदलता है, जबकि gsub सबको बदलता है।
In this page:
Syntax
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
text <- "cat bat cat sat"
cat(sub("cat", "dog", text), "\n")
cat(gsub("cat", "dog", text), "\n")
cat(gsub("[aeiou]", "*", text), "\n")
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
subइस्तेमाल करना और हर match बदलने की उम्मीद करना, जब यह सिर्फ पहला replace करता है;gsubइस्तेमाल करें।- pattern में
.या+को plain characters की तरह इस्तेमाल करना, जब वे regex symbols हैं;fixed = TRUEइस्तेमाल करें या\\.से escape करें। - argument order swap करना, जब pattern पहले आता है, फिर replacement और फिर text।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: