A
A
Alexander Petrov2021-03-27 11:45:32
ruby
Alexander Petrov, 2021-03-27 11:45:32

How to split a string in ruby ​​on the first occurrence or on a specific word?

Let's say there is a string "one word and many words in a sentence".

If I do , then the result will be . And you need to get :. That is, split by the first occurrence found in the string. Or split the string exactly by the word word, and if there are more letters in the word, then this is not considered a match. str.split('word')['one ', ' and many ','s in a sentence']

['one ', ' and many words in a sentence']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Mirilaczvili, 2021-03-27
@Mirkom63

Using the regular expression \bword\b, where \bmeans a word boundary:
str.split(/\bword\b/)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question