简体   繁体   English

在 Ruby 中返回字符串直到匹配的字符串

[英]Return string until matched string in Ruby

How do you return the portion of a string until the first instance of " #" or " Apt" ?如何返回字符串的一部分,直到" #"" 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.我知道我可以将字符串拆分为基于"#""Apt"的数组,然后调用.first ,但必须有更简单的方法。

String splitting is definitely easier and more readable that a regex.字符串拆分绝对比正则表达式更容易、更易读。 For regex, 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.使用String#[]方法。 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我不会用 ruby​​ 写那么多,但我相信你可以使用正则表达式

^.*(#|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.或者,如果您将字符串放入标记器中,您可以用它做一些事情,但考虑到您正在寻找一个单词而不仅仅是一个字符,这会更困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM