gsub और sub
sub और gsub text में एक pattern ढूंढते हैं और इसे किसी दूसरी चीज़ से swap करते हैं, एक document में Find and Replace की तरह। sub सिर्फ पहला match बदलता है, जबकि gsub सबको बदलता है।
In this page:
Syntax
string.sub(pattern, replacement)
string.gsub(pattern, replacement)
gsub और sub
sub(pattern, replacement) एक string में एक pattern का पहला match replace करता है, और gsub() हर match replace करता है (global substitute)।
दोनों pattern की तरह या तो एक literal string या एक regular expression accept करते हैं, और एक block form आपको replacement dynamically compute करने देता है। ज़्यादातर Ruby string methods की तरह, ये एक नई string return करते हैं जब तक आप ! version (gsub!) इस्तेमाल न करें।
Note:
gsub एक block form accept करता है, जैसे
text.gsub(/\\d+/) { |n| n.to_i * 2 }, आपको हर replacement dynamically compute करने देते हुए।उदाहरण: gsub and sub
text = "cat bat cat sat"
puts text.sub("cat", "dog")
puts text.gsub("cat", "dog")
puts text.gsub(/[aeiou]/, "*")
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इस्तेमाल करना और सारे matches बदलने की उम्मीद करना, जब सिर्फ पहला बदलता है;gsubइस्तेमाल करें।- यह उम्मीद करना कि
text.gsub(...)textबदल देगा, जब यह एक नई string return करता है जब तक आपgsub!इस्तेमाल न करें। - regex symbols वाली एक string को एक pattern की तरह इस्तेमाल करना, जैसे
".", जो एक regex में किसी भी character से match करता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: