gpt4 book ai didi

ruby - 如何从 Ruby 中的字符串中抓取文本片段?

转载 作者:数据小太阳 更新时间:2023-10-29 08:33:48 26 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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[@#]))/]

关于ruby - 如何从 Ruby 中的字符串中抓取文本片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8767516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com