Ruby - String Replace by Regular Expression

Introduction

To replace the first two characters of a string with 'Hello':

Demo

x = "This is a test" 
puts x.sub(/^../, 'Hello')

Result

Here, you make a single substitution with sub.

The first parameter given to sub isn't a string but a regular expression.

The forward slashes are used to start and end a regular expression.

Within the regular expression is ^...

The ^ is an anchor, meaning the regular expression will match from the beginning of any lines within the string.

The two periods each represent "any character."

/^../ means "any two characters immediately after the start of a line."

Therefore, Th of "This is a test" gets replaced with Hello.

To change the last two letters:

Demo

x = "This is a test" 
puts x.sub(/..$/, 'Hello')

Result

The regular expression matches the two characters that are anchored to the end of any lines within the string.

To anchor to the absolute start or end of a string, use \A and \Z, respectively.

^ and $ anchor to the starts and ends of lines within a string.

Related Topic