ruby regex - 如何匹配所有字符直到字符 -

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6538884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:29:59  来源:igfitidea点击:

ruby regex - how to match everything up till the character -

ruby-on-railsrubyregexruby-on-rails-3

提问by TheExit

given a string as follow:

给定一个字符串,如下所示:

randomstring1-randomstring2-3df83eeff2

How can I use a ruby regex or some other ruby/rails friendly method to find everything up until the first dash -

我如何使用 ruby​​ 正则表达式或其他一些 ruby​​/rails 友好的方法来查找所有内容,直到第一个破折号 -

In the example above that would be: randomstring1

在上面的例子中,这将是:randomstring1

Thanks

谢谢

回答by Kirill Polishchuk

You can use this pattern: ^[^\-]*

您可以使用此模式: ^[^\-]*

回答by agent-j

mystring = "randomstring1-randomstring2-3df83eeff2"
firstPart = mystring[0, mystring.index("-")]

Otherwise, I think the best regex is @polishchuk's.

否则,我认为最好的正则表达式是@polishchuk's。

It matches from the beginning of the string, matches as many as possible of anything that is not a dash -.

它从字符串的开头匹配,匹配尽可能多的不是 dash 的任何内容-

回答by Pash

Using irb you can do this too:

使用 irb 你也可以这样做:

>> a= "randomstring1-randomstring2-3df83eeff2"
=> "randomstring1-randomstring2-3df83eeff2"
>> a.split('-').first
=> "randomstring1"
>> 

回答by Mark Wilkins

For this situation, the index solution given by agent-j is probably better. If you did want to use regular expressions, the following non-greedy (specified by the ?) regex would grab it:

对于这种情况,agent-j 给出的索引解决方案可能会更好。如果您确实想使用正则表达式,以下非贪婪(由 指定?)正则表达式将获取它:

(^.*?)-

You can see it in Rubular.

您可以在Rubular 中看到它。