User Guide #05 - Ruby - Regular expressions

regular expressions, Ruby, ruby lesson, ruby уроки, user guide, регулярные выражения, руководство пользователя

Let's put together a more interesting program. This time we test whether a string fits a description, encoded into a concise pattern .

There are some characters and character combinations that have special meaning in these patterns, including:

[] - range specificication (e.g., [a-z] means a letter in the range a to z)
\w - letter or digit; same as [0-9A-Za-z]
\W - neither letter or digit
\s - space character; same as [ \t\n\r\f]
\S - non-space character
\d - digit character; same as [0-9]
\D - non-digit character
\b - backspace (0x08) (only if in a range specification)
\b - word boundary (if not in a range specification)
\B - non-word boundary
* - zero or more repetitions of the preceding
+ - one or more repetitions of the preceding
{m,m} - at least m and at most n repetitions of the preceding
? - at most one repetition of the preceding; same as {0,1}
| - either preceding or next expression may match
() - grouping

The common term for patterns that use this strange vocabulary is regular expressions . In ruby, as in Perl, they are generally surrounded by forward slashes rather than double quotes. If you have never worked with regular expressions before, they probably look anything but regular , but you would be wise to spend some time getting familiar with them. They have an efficient expressive power that will save you headaches (and many lines of code) whenever you need to do pattern matching, searching, or other manipulations on text strings.

For example, suppose we want to test whether a string fits this description: "Starts with lower case f, which is immediately followed by exactly one upper case letter, and optionally more junk after that, as long as there are no more lower case characters." If you're an experienced C programmer, you've probably already written about a dozen lines of code in your head, right? Admit it; you can hardly help yourself. But in ruby you need only request that your string be tested against the regular expression /^f[A-Z](^[a-z])*$/.

How about "Contains a hexadecimal number enclosed in angle brackets"? No problem.

ruby> def chab(s)   # "contains hex in angle brackets"
    |    (s =~ /<0(x|X)(\d|[a-f]|[A-F])+>/) != nil
    | end
ruby> chab "Not this one."
ruby> chab "Maybe this? {0x35}"    # wrong kind of brackets
ruby> chab "Or this? <0x38z7e>"    # bogus hex digit
ruby> chab "Okay, this: <0xfc0004>."

Though regular expressions can be puzzling at first glance, you will quickly gain satisfaction in being able to express yourself so economically.

Here is a little program to help you experiment with regular expressions. Store it as regx.rb and run it by typing "ruby regx.rb" at the command line.

# Requires an ANSI terminal!

st = "\033[7m"
en = "\033[m"

while TRUE
  print "str> "
  str = gets
  break if not str
  print "pat> "
  re = gets
  break if not re
  str.gsub! re, "#{st}\\&#{en}"
  print str, "\n"
print "\n"

The program requires input twice, once for a string and once for a regular expression. The string is tested against the regular expression, then displayed with all the matching parts highlighted in reverse video. Don't mind details now; an analysis of this code will come soon.

str> foobar
pat> ^fo+

Matches part was marked the following line "~~~".

Let's try several more inputs.

str> abc012dbcd555
pat> \d
   ~~~    ~~~

If that surprised you, refer to the table at the top of this page: \d has no relationship to the character d , but rather matches a single digit.

What if there is more than one way to correctly match the pattern?

str> foozboozer
pat> f.*z

foozbooz is matched instead of just fooz ,since a regular expression maches the longest possible substring.

Here is a pattern to isolate a colon-delimited time field.

str> Wed Feb  7 08:58:04 JST 1996
pat> [0-9]+:[0-9]+(:[0-9]+)?
Wed Feb  7 08:58:04 JST 1996

"=~" is a matching operator with respect to regular expressions; it returns the position in a string where a match was found, or nil if the pattern did not match.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

April 6, 2020, 5:24 a.m.

C++ - Test 001. The first program and data types

  • Result:86points,
  • Rating points6
April 5, 2020, 2:32 p.m.

C++ - Test 002. Constants

  • Result:91points,
  • Rating points8
April 5, 2020, 2:31 p.m.
Alexander Peshkov

C++ - Test 001. The first program and data types

  • Result:60points,
  • Rating points-1
Last comments
April 3, 2020, 8:06 a.m.
Konstantin Grudnitskiy

Я надеюсь вы уже разобрались в чем дело, но если вдруг нет, то проблема состоит в том, что вы пытаетесь запустить программу из интерпретатора питона. Файл это уже готова…
April 3, 2020, 6:18 a.m.
Konstantin Grudnitskiy

>>> text = 'hello world'>>> ' '.join(word for word in text.split()[:-1])'hello'>>> def remove_last_word(text):... return text and ' '.join(word for word in text.s…
March 27, 2020, 2:40 p.m.
Evgenij Legotskoj

Добрый день. В конце пятой статьи скачать можете.
March 27, 2020, 2:28 p.m.
mkdir _

Здравствуйте, а можно, пожалуйста, ссылку на целые исходники, если есть?
March 27, 2020, 4:36 a.m.
Evgenij Legotskoj

Скорее всего также, как и для установки всех остальных переменых в CMake, через использование set
Now discuss on the forum
April 6, 2020, 4:19 a.m.
Evgenij Legotskoj

Попробуй не переустанавливать материал, а просто менять цвет
April 6, 2020, 3:39 a.m.
Evgenij Legotskoj

Добрый день. Это всё работает, вот только если есть переопределения каких-то методов, то нет гарантии, что что-то не сломается. Думаю, что нужно допиливать стилевоё оформление в прокси…
April 5, 2020, 11:38 a.m.

Так работает windeployqt --qmldir E:\QTProject\testQmlAndCpp E:\test\build-testQmlAndCpp-Desktop_Qt_5_14_1_MinGW_32_bit-Release
April 5, 2020, 2:35 a.m.

Так работает console.log(textEmail.text) var str = textEmail.text; var n =^((([0-9A-Za-z]{1}[-0-9A-z\.]{1,}[0-9A-Za-z]{1})|([0-9А-Яа-я]{1}[-0-9А-я\.]{1,}[…
April 3, 2020, 8:48 a.m.

Евгений, добрый день. Спасибо!
© EVILEG 2015-2019
Recommend hosting TIMEWEB