【问题标题】:How do I grab pieces of text from a string in Ruby?如何从 Ruby 中的字符串中获取文本片段?
【发布时间】:2012-02-04 18:05:39
【问题描述】:

如果用户提交如下字符串:

我的客厅计划#plans #livingroom @cbmeeks #design @moe @larry - 这太酷了!

我想要以下数组/字符串:

text = "My living room plans"
tags = ['plans', 'livingroom', 'design']
people = ['cbmeeks', 'moe', 'larry']
description = "this is cool!"

每个提交的字符串都以text 开头。没有@- 等。我不必担心用户以标签或人开头。细分应该看起来像这样,除了 TEXT 总是在第一位之外,任何顺序都可以。

TEXT [-description] [#tags] [@people]

编辑 我似乎无法弄清楚如何正确抓住它们。例如:

a = "My living room plans #plans #livingroom @cbmeeks #design @moe @larry -this is cool!"

/#\w+/.match(a).to_a
#=> ["#plans"] -- only grabs first one

【问题讨论】:

  • 你能告诉我们你到目前为止写了什么吗?
  • a.scan /..../ 是你要找的。​​span>

标签: ruby string text-parsing


【解决方案1】:
input = "My living room plans #plans #livingroom @cbmeeks #design @moe @larry -this is cool!"
text = input.match('^(.*?)#')[1]
tags = input.scan(/#(.*?) /)
people = input.scan(/@(.*?) /)
description = input.match('-(.*?)$')[1]

【讨论】:

  • 这不会以任何顺序匹配,也不会去除前面的符号。
  • 谢谢。这几乎是完美的。比我想象的要好得多。
【解决方案2】:

这将自动删除#@-,并以任意顺序匹配:

string = "My living room plans #plans #livingroom @cbmeeks #design @moe @larry -this is cool!"
text = string[/^(.*?)+(?=\s[@#-])/]
tags = string.scan /(?<=#)\w+/
people = string.scan /(?<=@)\w+/
description = string[/(?<=-)(.*?)+?(?=($|\s[@#]))/]

【讨论】:

  • 感谢你们两个,但这太棒了,正是我想要的。我的正则表达式技能很弱。如果你能解释它是如何工作的,我想再给你 100 分。比如(?&lt;=-) 是干什么用的?我假设其中的- 是因为描述以- 开头。谢谢
  • ?&lt;= 是一个后视。这意味着仅匹配以指定字符开头的单词,但不包括该实际字符。所以(?&lt;=-) 会找到一个以破折号 (-) 开头的字符串,但不包括破折号。
  • 我确信有一种方法可以避免使用 strip 并使用正则表达式删除尾随空格,但我的正则表达式技能并不是非常先进。
  • 顺便说一下,look-behinds 仅在 Ruby 1.9 中有效,在 1.8 或更早版本中无效。
  • +1000 给你。我正在使用 1.9,并且在我将字符串弄乱后确认它仍然有效。 完美再次感谢。
【解决方案3】:
str = 'My living room plans #plans #livingroom @cbmeeks #design @moe @larry -this is cool!'

text = str[/^([^#\@]+)/, 1].strip # => "My living room plans"
str.sub!(text, '') # => " #plans #livingroom @cbmeeks #design @moe @larry -this is cool!"

tags        = str.scan( /#([a-z0-9]+)/ ).flatten # => ["plans", "livingroom", "design"]
people      = str.scan( /@([a-z0-9]+)/ ).flatten # => ["cbmeeks", "moe", "larry"]
description = str.scan( /-(.+)/        ).flatten # => ["this is cool!"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多