Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the first 4 characters from a string if it matches a pattern in Ruby

Tags:

string

regex

ruby

I have the following string:

"h3. My Title Goes Here" 

I basically want to remove the first four characters from the string so that I just get back:

"My Title Goes Here".  

The thing is I am iterating over an array of strings and not all have the h3. part in front so I can't just ditch the first four characters blindly.

I checked the docs and the closest thing I could find was chomp, but that only works for the end of a string.

Right now I am doing this:

"h3. My Title Goes Here".reverse.chomp(" .3h").reverse

This gives me my desired output, but there has to be a better way. I don't want to reverse a string twice for no reason. Is there another method that will work?

like image 228
James Avatar asked Feb 27 '23 23:02

James


1 Answers

To alter the original string, use sub!, e.g.:

my_strings = [ "h3. My Title Goes Here", "No h3. at the start of this line" ]
my_strings.each { |s| s.sub!(/^h3\. /, '') }

To not alter the original and only return the result, remove the exclamation point, i.e. use sub. In the general case you may have regular expressions that you can and want to match more than one instance of, in that case use gsub! and gsub—without the g only the first match is replaced (as you want here, and in any case the ^ can only match once to the start of the string).

like image 96
Arkku Avatar answered Mar 01 '23 16:03

Arkku