我有一堆句子想分成一個陣列。現在,每次 \n 出現在字串中時,我都會拆分。
@chapters = @script.split('\n')
我想做的是 .split ever OTHER "." 在字串中。這在 Ruby 中可能嗎?
uj5u.com熱心網友回復:
你可以用正則運算式來做,但我會從一個簡單的方法開始:只分割句點,然后連接成對的子字串:
s = "foo. bar foo. foo bar. boo far baz. bizzle"
s.split(".").each_slice(2).map {|p| p.join "." }
# => => ["foo. bar foo", " foo bar. boo far baz", " bizzle"]
uj5u.com熱心網友回復:
在這種情況下,使用String#scan比使用String#split更容易。
我們可以使用下面的正則運算式:
r = /(?<=\.|\A)[^.]*\.[^.]*(?=\.|\z)/
str=<<~_
Now is the time. This is it. It is now. The time to have fun.
The time to make new friends. The time to party.
_
str.scan(r)
#=> [
# "Now is the time. This is it",
# " It is now. The time to have fun",
# "\nThe time to make new friends. The time to party"
#=> ]
我們可以以自由間距模式撰寫正則運算式,使其自檔案化。
r = /
(?<= # begin a positive lookbehind
\A # match the beginning of the string
| # or
\. # match a period
) # end positive lookbehind
[^.]* # match zero or more characters other than periods
\. # match a period
[^.]* # match zero or more characters other than periods
(?= # begin a positive lookahead
\. # match a period
| # or
\z # match the end of the string
) # end positive lookahead
/x # invoke free-spacing regex definition mode
請注意,(?<=\.|\A)可以替換為(?<![^\.])。(?<![^\.])是一個否定的回顧,它斷言匹配前面沒有除句點以外的字符。
同樣,(?=\.|\z)可以替換為(?![^.]). (?![^.])是一個否定前瞻,斷言匹配后沒有除句點以外的字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/534551.html
