简体   繁体   English

ruby 正则表达式 - 如何匹配直到字符的所有内容 -

[英]ruby regex - how to match everything up till the character -

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谢谢

You can use this pattern: ^[^\-]*您可以使用此模式: ^[^\-]*

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 - .它从字符串的开头开始匹配,尽可能多地匹配任何不是破折号-的内容。

Using irb you can do this too:使用 irb 你也可以这样做:

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

For this situation, the index solution given by agent-j is probably better.对于这种情况,agent-j 给出的索引解决方案可能会更好。 If you did want to use regular expressions, the following non-greedy (specified by the ? ) regex would grab it:如果您确实想使用正则表达式,则以下非贪婪(由?指定)正则表达式会抓住它:

(^.*?)-

You can see it in Rubular .您可以在Rubular中看到它。

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

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