gsub and sub
sub and gsub find a pattern in text and swap it for something else, like Find and Replace in a document. sub changes only the first match, while gsub changes them all.
In this page:
Syntax
string.sub(pattern, replacement)
string.gsub(pattern, replacement)
gsub and sub
sub(pattern, replacement) replaces the first match of a pattern in a string, and gsub() replaces every match (global substitute).
Both accept either a literal string or a regular expression as the pattern, and a block form lets you compute the replacement dynamically. Like most Ruby string methods, they return a new string unless you use the ! version (gsub!).
Note:
gsub accepts a block form, like
text.gsub(/\\d+/) { |n| n.to_i * 2 }, letting you compute each replacement dynamically.Example: 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. #}
Common Mistakes
- Using
suband expecting all matches to change, when only the first does; usegsub. - Expecting
text.gsub(...)to changetext, when it returns a new string unless you usegsub!. - Using a string as a pattern that contains regex symbols, such as
".", which in a regex matches any character.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: