如何使用ruby生成子字符串

如何使用ruby生成子字符串,ruby,substring,Ruby,Substring,我在ruby中有以下字符串值: response = localhost:8080/test1 and xxx: foopbar, 我需要以下格式的输出,如 response = localhost:8080/test1 应删除after和所有字符串值,并仅给出localhost:8080/test1。有人能帮助我们在Ruby中实现这一点吗。谢谢你的帮助 在这种情况下,一个简单的正则表达式应该可以做到: response = "localhost:8080/test1 and xxx: fo

我在ruby中有以下字符串值:

response = localhost:8080/test1 and xxx: foopbar,
我需要以下格式的输出,如

response = localhost:8080/test1

应删除after和所有字符串值,并仅给出localhost:8080/test1。有人能帮助我们在Ruby中实现这一点吗。谢谢你的帮助

在这种情况下,一个简单的正则表达式应该可以做到:

response = "localhost:8080/test1 and xxx: foopbar"
response.gsub(/ and .+$/,'')  # returns => "localhost:8080/test1"

用于修改接收器,即responseThanks!我在这里再次尝试相同的操作,但不起作用,我有一个字符串localhost:8080/test1 xxx:foopbar,我尝试使用以下代码删除xxx和该字符串的其余部分,但它没有按预期工作:response=value.gsub/xxx.+$/。你能告诉我这里做错了什么吗你的字符串包含一个冒号:在xxx之后,所以你应该将正则表达式改为/xxx.+$/删除最后一个“x”之后的空格这可能是无效的Ruby。。。它可能需要一些引用。