Reputation: 220
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?
Upvotes: 4
Views: 5507
Reputation: 838786
You can use sub with a regular expression:
s = 'h3. foo'
s.sub!(/^h[0-9]+\. /, '')
puts s
Output:
foo
The 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 modify the regular expression to suit your needs. See a regular expression tutorial or syntax guide, for example here.
Upvotes: 3
Reputation: 42149
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).
Upvotes: 3
Reputation: 40553
A standard approach would be to use regular expressions:
"h3. My Title Goes Here".gsub /^h3\. /, '' #=> "My Title Goes Here"
gsub
means globally substitute and it replaces a pattern by a string, in this case an empty string.
The regular expression is enclosed in /
and constitutes of:
^
means beginning of the string
h3
is matched literally, so it means h3
\.
- a dot normally means any character so we escape it with a backslash
is matched literally
Upvotes: 2