Home > Software engineering >  How to match any pattern to a any string using Ruby?
How to match any pattern to a any string using Ruby?

Time:10-24

I would like to create a function in Ruby which accepts the following parameters:

  • A pattern string (e.g. "abab", "aabb", "aaaa", etc.)
  • An input string (e.g. "dogcatdogcat", "carcarhousehouse", etc.)

The return of the function should be "true" if the string matches the pattern and "false" if not.

My approach for the first step:

Use regex in order to separate the input string into an array of words (e.g. ["dog", "cat", "dog", "cat"]).

My regex expertise is not good enough to be able to find the right regex for this problem.

Does anyone know how to perform the appropriate regex so that recurring words get separated assuming the input string is always some form of pattern?

CodePudding user response:

You can use capture groups and backreferences to match the same substring multiple times, e.g.:

abab = /\A(. )(. )\1\2\z/
aabb = /\A(. )\1(. )\2\z/
aaaa = /\A(. )\1\1\1\z/

'dogcatdogcat'.match?(abab) #=> true
'dogcatdogcat'.match?(aabb) #=> false
'dogcatdogcat'.match?(aaaa) #=> false

'carcarhousehouse'.match?(abab) #=> false
'carcarhousehouse'.match?(aabb) #=> true
'carcarhousehouse'.match?(aaaa) #=> false

In the above pattern, (. ) defines a capture group that matches one or more characters. \1 then refers to the 1st capturing group and matches the same substring. (\2 is the 2nd group and so on)

\A and \z are anchors to match the beginning and end of the string.

  • Related