Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby字符串匹配到-&引用;_Ruby_Regex - Fatal编程技术网

Ruby字符串匹配到-&引用;

Ruby字符串匹配到-&引用;,ruby,regex,Ruby,Regex,我有一个类似于string1=“foo-bar0164”的字符串,我希望将所有字符存储到变量中的“-”。在这个例子中,只有“foo” 我的尝试是: string1.match(/([^-]+)/) 但它确实匹配除-以外的所有字符。试试这个 string1.match(/(.*)-/).captures => ["foo"] 或 试试这个 string1.match(/(.*)-/).captures => ["foo"] 或 您可以尝试匹配/([^-]+)-/。这将确保匹配在第

我有一个类似于
string1=“foo-bar0164”
的字符串,我希望将所有字符存储到变量中的“-”。在这个例子中,只有“foo”

我的尝试是:

string1.match(/([^-]+)/)
但它确实匹配除-以外的所有字符。

试试这个

string1.match(/(.*)-/).captures
=> ["foo"]

试试这个

string1.match(/(.*)-/).captures
=> ["foo"]


您可以尝试匹配
/([^-]+)-/
。这将确保匹配在第一个
-
字符中结束。

您可以尝试匹配
/([^-]+)-/
。这将确保匹配在第一个
-
字符中结束。

此正则表达式将匹配模式[-]

^([\w]*)-([\w\d]*)$
使用()时,无法获得-前后字母的匹配组1和2

一个更快、更常见的解决方案是
string.split(“-”[0]
——您将得到它的第一部分作为
string
——但要注意空指针(长度应大于1或至少为空字符串)



我想检查我的正则表达式

此正则表达式将匹配模式[-]

^([\w]*)-([\w\d]*)$
使用()时,无法获得-前后字母的匹配组1和2

一个更快、更常见的解决方案是
string.split(“-”[0]
——您将得到它的第一部分作为
string
——但要注意空指针(长度应大于1或至少为空字符串)



我喜欢检查我的正则表达式

一些具有积极前瞻性的内容:

string1[/\A.*?(?=-)/] #=> "foo"

具有积极前瞻性的事物:

string1[/\A.*?(?=-)/] #=> "foo"

这种简单的方式怎么样:

> string1.split("-").first
#=> "foo" 

这种简单的方式怎么样:

> string1.split("-").first
#=> "foo" 

如果已知字符串包含连字符

str = "1234-567"
str[0,str.index('-)]
  #=> "1234"
如果不是

str_len = str.index('-)
str_len ? str[0,str_len] : nil

请注意,此方法既不使用正则表达式,也不创建临时数组。

如果已知字符串包含连字符

str = "1234-567"
str[0,str.index('-)]
  #=> "1234"
如果不是

str_len = str.index('-)
str_len ? str[0,str_len] : nil

请注意,此方法既不使用正则表达式,也不创建临时数组。

为什么不简单地
string1.split('-')。首先
?您的代码已经在做您想做的事情,即在
foo-bar0164
中捕获
foo
。如果您还想捕获连字符,下面有一个答案。否则,您能完成您的问题吗?“但它与除
-
之外的所有字符都匹配”--因为在
regex
中没有任何东西与
-
匹配。对于这个简单的用例,
Regexp
将比@MarekLipka建议的
拆分
或其他
字符串
方法(类似于拆分)或
切片
慢很多(例如
string1.slice(0,string1.index('-'))
)为什么不简单地
string1.split('-')。首先
?您的代码已经在做您想做的事情,即在
foo-bar0164
中捕获
foo
。如果您也想捕获连字符,下面有一个答案。否则,您能完成您的问题吗?“但它确实匹配所有字符,除了
-
”——因为在
regex
中没有匹配
-
的字符。对于这个简单的用例,
Regexp
将比@MarekLipka或其他
String
方法(如
partition
(类似于拆分)或
slice
(例如
string1.slice(0,string1.index('-'))