How to Use sub with Regex in Ruby: Simple Guide
In Ruby, you can use
sub with a regular expression to replace the first occurrence of a pattern in a string. The syntax is string.sub(/pattern/, 'replacement'), where the regex matches the part to change and the replacement is the new text.Syntax
The sub method replaces the first match of a regular expression in a string with a specified replacement.
string: The original text you want to change./pattern/: The regular expression that finds the text to replace.'replacement': The new text that will replace the matched part.
ruby
string.sub(/pattern/, 'replacement')Example
This example shows how to replace the first word starting with 'cat' in a sentence using sub with a regex.
ruby
sentence = "The cat chased the caterpillar." new_sentence = sentence.sub(/cat\w*/, 'dog') puts new_sentence
Output
The dog chased the caterpillar.
Common Pitfalls
One common mistake is expecting sub to replace all matches, but it only replaces the first one. Use gsub to replace all occurrences.
Also, forgetting to use regex delimiters / / can cause errors or unexpected behavior.
ruby
text = "apple apple apple" # Wrong: Using sub but expecting all replaced puts text.sub(/apple/, "orange") # Right: Using gsub to replace all puts text.gsub(/apple/, "orange")
Output
orange apple apple
orange orange orange
Quick Reference
sub(/regex/, 'text'): Replace first match only.gsub(/regex/, 'text'): Replace all matches.- Use
/pattern/to define regex. - Replacement can be a string or a block for dynamic changes.
Key Takeaways
Use
sub with regex to replace only the first matching part of a string.Always wrap your pattern in
/ / to use regex with sub.For replacing all matches, use
gsub instead of sub.You can use a block with
sub for more complex replacements.Remember
sub returns a new string; it does not change the original string unless you use sub!.