AndreyS AndreyS - 6 months ago 13
Ruby Question

Words including given string in Ruby

I'm writing little Rails api application, and I need to analyze string to find words having given string like:

Assuming my source text is

hello mr one two three four nine nineteen
and I want to check occurence of
, it will produce:
, and if I'll check occurence of
ne t
in the same string it will result in
one two

I know there is an ugly way with substrings, counting positions and parsing string this way, but I think it can be solved with regex scan.

Please say if you need some additional information, thanks.

▶ str = 'hello mr one two three four nine nineteen'
#⇒ "hello mr one two three four nine nineteen"
▶ re = ->(pattern) { /\p{L}*#{pattern}\p{L}*/ }
▶ str[re.('ne t')]
#⇒ "one two"
▶ str[re.('on')]
#⇒ "one"

Matcher \p{L} is generally better than \w and, especially, \S because it matches all utf-8 letters.

To match accented letters as well (i. e. combined in “naïve”,) one should extend left and right matchers:

▶ re = ->(pattern) { /[\p{L}\p{Mc}]*#{pattern}[\p{L}\p{Mc}]*/ }

Please note, that code above will return the first match. To return all matches, use String#scan instead of String#[]:

▶ str.scan re.('ni')
#⇒ ["nine", "nineteen"]