简体   繁体   English

如何在字符串中找到@ [XX:XXXX]的所有实例,然后找到周围的文本?

[英]How to find all instances of @[XX:XXXX] in a string and then find the surrounding text?

Given a string like: 给定一个像这样的字符串:

"@[19:Sara Mas] what's the latest with the TPS report? @[30:Larry Peters] can you help out here?"

I want to find a way to dynamically return, the user tagged and the content surrounding. 我想找到一种动态返回,标记用户和周围内容的方法。 Results should be: 结果应该是:

user_id: 19
copy: what's the latest with the TPS report?

user_id: 30
copy: can you help out here?

Any ideas on how this can be done with ruby/rails? 关于如何使用红宝石/铁轨有什么想法? Thanks 谢谢

How is this regex for finding matches? 这个正则表达式如何找到匹配?

@\[\d+:\w+\s\w+\]

Split the string, then handle the content iteratively. 拆分字符串,然后迭代处理内容。 I don't think it'd take more than: 我认为这不仅仅需要:

tmp = string.split('@').map {|str| [str[/\[(\d*).*/,1], str[/\](.*^)/,1]] }
tmp.first #=> ["19", "what's the latest with the TPS report?"]

Does that help? 这有帮助吗?

result = subject.scan(/\[(\d+).*?\](.*?)(?=@|\Z)/m)

This grabs id and content in backreferences 1 and 2 respectively. 这分别在后向引用1和2中获取id和内容。 For stoping the capture either @ or the end of string must be met. 要停止捕获,必须满足@或字符串结尾。

 "
\\[         # Match the character “[” literally
(          # Match the regular expression below and capture its match into backreference number 1
   \\d         # Match a single digit 0..9
      +          # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
.          # Match any single character that is not a line break character
   *?         # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
\\]         # Match the character “]” literally
(          # Match the regular expression below and capture its match into backreference number 2
   .          # Match any single character that is not a line break character
      *?         # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
)
(?=        # Assert that the regex below can be matched, starting at this position (positive lookahead)
              # Match either the regular expression below (attempting the next alternative only if this one fails)
      \@          # Match the character “\@” literally
   |          # Or match regular expression number 2 below (the entire group fails if this one fails to match)
      \$          # Assert position at the end of the string (or before the line break at the end of the string, if any)
)
"

This will match something starting from @ and ending to punctuation makr. 这将匹配从@开头到标点符号makr的内容。 Sorry if I didn't understand correctly. 对不起,如果我没有正确理解。

result = subject.scan(/@.*?[.?!]/)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM