开发者

Regex to extract all matches of several patterns from a single string in Ruby

开发者 https://www.devze.com 2023-02-08 10:44 出处:网络
After three hours I\'m going to stop banging my head on the wall and ask for help. This ought to be an easy regex, but I just can\'t quite get my mind around it today.

After three hours I'm going to stop banging my head on the wall and ask for help. This ought to be an easy regex, but I just can't quite get my mind around it today.

Given a short string and a few different patterns, I need to extract all the matching patterns from the string, where each pattern is a "whole word".

The patterns are开发者_如何学Python: "YES", "NO", "MAYBE", any sequence of asterisks ['*', '**', '***', '...'], any number from 0 to 999, with the case of the text being case-insensitive.

So if s = 'foo yes and no doo 5 boo **** bar far 13 not but no' the result would be ["yes", "no", "5", "****", "13", "no"]


s = 'foo yes and no doo 5 boo * *** bar far 13 not but no YESTERDAY'
ms = s.scan(/(?:\b(?:yes|no|\d{1,3})\b|\*+)/i)
ms # => ["yes", "no", "5", "*", "***", "13", "no"]
0

精彩评论

暂无评论...
验证码 换一张
取 消