1.17. Dopasowywanie łańcuchów za pomocą wyrażeń regularnych

Problem

Chcemy sprawdzić, czy dany łańcuch zgodny jest z pewnym wzorcem.

Rozwiązanie

Wzorce są zwykle definiowane za pomocą wyrażeń regularnych. Zgodność („pasowanie”) łańcucha z wyrażeniem regularnym testowane jest przez operator =~.

string = 'To jest łańcuch 27-znakowy.'
if string =~ /([0-9]+)-character/ and $1.to_i == string.length
  "Tak, to jest łańcuch #$1-znakowy."
end
# "Tak, to jest łańcuch 27-znakowy."

Można także użyć metody Regexp#match:

match = Regexp.compile('([0-9]+)-znakowy').match(string)
if match && match[1].to_i == string.length
  "Tak, to jest łańcuch #{match[1]}-znakowy."
end
# "Tak, to jest łańcuch 27-znakowy."

Za pomocą instrukcji case można sprawdzić zgodność ...

Get Ruby. Receptury now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.