开发者

Return string until matched string in Ruby

开发者 https://www.devze.com 2023-04-06 16:59 出处:网络
How do you return the portion of a string开发者_运维技巧 until the first instance of \" #\" or \" Apt\"?

How do you return the portion of a string开发者_运维技巧 until the first instance of " #" or " Apt"?

I know I could split the string up into an array based on "#" or "Apt" and then calling .first, but there must be a simpler way.


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


I'd write a method to make it clear. Something like this, for example:

class String
    def substring_until(substring)
        i = index(substring)
        return self if i.nil?
        i == 0 ? "" : self[0..(i - 1)]
    end
end


Use String#[] method. Like this:

[
  '#foo',
  'foo#bar',
  'fooAptbar',
  'asdfApt'
].map { |str| str[/^(.*)(#|Apt)/, 1] } #=> ["", "foo", "foo", "asdf"]


I don't write in ruby all that much, but I'm sure you could use a regular expression along the lines of

^.*(#|Apt)

Or, if you put the string into a tokenizer, you could do something with that, but it'd be tougher considering you are looking for a word and not just a single character.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号