Bắt đầu ngayBắt đầu miễn phí

Repetition

The rebus functions one_or_more(), zero_or_more() and optional() can be used to wrap parts of a regular expression to allow a pattern to match a variable number of times.

Take our vowels pattern from the last exercise. You can pass it to one_or_more() to create the pattern that matches "one or more vowels". Take a look with these interjections:

x <- c("ow", "ooh", "yeeeah!", "shh")
str_view(x, pattern = one_or_more(vowels))

You'll see we can match the single o in ow, the double o in ooh and the string of es followed by the a in yeeeah, but nothing in shh because there isn't a single vowel.

In contrast zero_or_more() will match even if there isn't an occurrence, try

str_view(x, pattern = zero_or_more(vowels))

Since both yeeeah and shh start without a vowel, they match "zero vowels", and since regular expressions are lazy, they look no further and return the start of the string as a match.

Bài tập này là một phần của khóa học

String Manipulation with stringr in R

Xem khóa học

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

# Vowels from last exercise
vowels <- char_class("aeiouAEIOU")

# See names with only vowels
str_view(boy_names, 
  pattern = ___, 
  match = TRUE)
Chỉnh sửa và Chạy Mã