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

I have the following line:

"h3. My Title Goes Here" 

I basically want to remove the first four characters from the string, just to return:

 "My Title Goes Here". 

The thing is, I am repeating an array of strings, and not everyone has a h3. part h3. ahead, so I can't just drop the first four characters blindly.

I checked the docs and the closest thing I could find was chomp , but this only works for the end of the line.

Now I am doing this:

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

This gives me my desired result, but there should be a better way. I do not want to change the line twice for no reason. Is there any other way that will work?

+4
source share
3 answers

To change the original string, use sub! , eg:

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

In order not to change the source text and return the result, delete the exclamation mark, i.e. use sub . In general, you may have regular expressions that you can and want to map to more than one instance, in which case use gsub! and gsub - without g only the first match is replaced (as you want here, and in any case ^ can only match once at the beginning of the line).

+3
source

You can use sub with regex:

 s = 'h3. foo' s.sub!(/^h[0-9]+\. /, '') puts s 

Conclusion:

 foo 

A regular expression should be understood as follows:

  ^ Match from the start of the string.
 h A literal "h".
 [0-9] A digit from 0-9.
 + One or more of the previous (i.e. one or more digits)
 \.  A literal period.
       A space (yes, spaces are significant by default in regular expressions!)

You can change the regular expression to suit your needs. See the Regular Expression Guide or the Syntax Guide, for example here .

+3
source

A standard approach would be to use regular expressions :

 "h3. My Title Goes Here".gsub /^h3\. /, '' #=> "My Title Goes Here" 

gsub stands for global replacement and replaces the template with a string, in this case an empty string.

The regular expression is enclosed in / and consists of:

^ means start of line
h3 matches literally, so h3 means
\. - period usually means any character, so we avoid it with a backslash
matches literally

+2
source

Source: https://habr.com/ru/post/1310625/


All Articles