How to Remove All Characters in a String Until a Substring Is Matched, in Ruby

How do I remove all characters in a string until a substring is matched, in Ruby?

or with the regex:

str = "Hey what's up @dude, @how's it going?"
str.gsub!(/.*?(?=@how)/im, "") #=> "@how's it going?"

you can read about lookaround at here

How do I remove a substring after a certain character in a string using Ruby?

new_str = str.slice(0..(str.index('blah')))

alt text

Select all characters in a string until a specific character Ruby

You can avoid creating an unnecessary Array (like Array#split) or using a Regex (like Array#gsub) by using.

a = "2.452811139617034,42.10874821716908|3.132087902867818,42.028314077306646|-0.07934861041448178,41.647538468746916|-0.07948265046522918,41.64754863599606"

a[0,a.index('|')]
#=>"2.452811139617034,42.1087482171"

This means select characters at positions 0 up to the index of the first pipe (|). Technically speaking it is start at position 0 and select the length of n where n is the index of the pipe character which works in this case because ruby uses 0 based indexing.

As @CarySwoveland astutely pointed out the string may not contain a pipe in which case my solution would need to change to

#to return entire string
a[0,a.index('|') || a.size]
# or
b = a.index(?|) ? a[0,b] : a
# or to return empty string
a[0,a.index('|').to_i]
# or to return nil
a[0,a.index(?|) || -1]

How to remove a certain character after substring in Ruby

If you don't want to use regex that sometimes difficult to understand use this:

def exclamation(sentence)
words = sentence.split
words_wo_exclams = words.map do |word|
word.split('').reverse.drop_while { |c| c == '!' }.reverse.join
end
words_wo_exclams.join(' ')
end

Return string until matched string in Ruby

String splitting is definitely easier and more readable than trying to extract the portion of the string using a regex. For the latter case, you would need a capture group to get the first match. It will be the same as string splitting

string.split(/#|Apt/, 2).first

Remove @ sign and everything after it in Ruby

To catch anything before the @ sign:

my_string = "user@example.com"
substring = my_string[/[^@]+/]
# => "user"

Remove substring from the string

You can use the slice method:

a = "foobar"
a.slice! "foo"
=> "foo"
a
=> "bar"

there is a non '!' version as well. More info can be seen in the documentation about other versions as well:
http://www.ruby-doc.org/core/classes/String.html#method-i-slice-21

Ruby - slice all characters till underscore in a string

"solution_10"[/(?<=_).*/]
#⇒ "10"

or simply just get digits until the end of the line:

"solution_10"[/\d+\z/]
#⇒ "10"


Related Topics



Leave a reply



Submit