【问题标题】:How to sub string using ruby如何使用 ruby​​ 子字符串
【发布时间】:2015-03-26 09:03:35
【问题描述】:

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

response = localhost:8080/test1 and xxx: foopbar,

我需要以下格式的输出,例如

response = localhost:8080/test1

“and”之后的所有字符串值都应该被删除并且只给出localhost:8080/test1。有人可以帮助如何在 Ruby 中实现这一点。感谢您的帮助!

【问题讨论】:

标签: ruby substring


【解决方案1】:

在这种情况下,一个简单的正则表达式应该可以解决问题:

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

【讨论】:

  • 使用gsub!修改接收者(即response
  • 谢谢!我在这里再次尝试但不工作,我有这个字符串 localhost:8080/test1 xxx: foopbar,我尝试使用以下代码删除 xxx 和字符串的其余部分,但它没有按预期工作:response = value。 gsub(/xxx .+$/,'') 。你能告诉我这里做错了什么吗
  • 你的rstring在“xxx”后面有一个冒号:,所以应该把正则表达式改成/ xxx.+$/(去掉最后一个“x”后面的空格)
猜你喜欢
  • 2011-05-28
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-31
  • 2012-01-05
  • 1970-01-01
相关资源
最近更新 更多