Help us understand the problem. What is going on with this article?

[Ruby]後読みを使ったsplitで句点(。)を残したまま文に分割

More than 1 year has passed since last update.

初投稿になります。

はじめに

Rubyで文章を一文ずつに分割して配列にしたい場合、
String#splitを使って句点'。'で区切ってやればいいですが、区切り文字として使った'。'が消えてしまいます。

後ろにまた付け直すこともできますが、面倒です。

text = 'おはよう。こんにちは。こんばんは。'

text.split('。')
# => ["おはよう", "こんにちは", "こんばんは"]

text.split('。').map{|s| s + '。'}
# => ["おはよう。", "こんにちは。", "こんばんは。"]

正規表現で後読みを使う

これには、String#splitに正規表現で「肯定的後読み」(?<= )を使ってやれば、区切り文字"。"を消さずに分割できます。

text = 'おはよう。こんにちは。こんばんは。'

text.split(/(?<=。)/)
# => ["おはよう。", "こんにちは。", "こんばんは。"]

scanメソッドでもできる

ちなみにString#scanを使ってもできます。

text = 'おはよう。こんにちは。こんばんは。'

text.scan(/.*?。/)
# => ["おはよう。", "こんにちは。", "こんばんは。"]

こちらのほうが簡単ですね。

参考にしたサイト

正規表現の先読み・後読みを極める!

wai-doi
Ruby / Rails / Agile / 自然言語処理 /
esm
We build applications which work well and make customers happy.
http://www.esm.co.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした