Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
str = "This\n is a sample text for test" str.scan(/\S.{0,15}\S(?=\s|$)|\S+/) # => ["This", "is a sample text", "for test"]
在这里,当出现换行符 ( \n) 时它会拆分。我实际上希望输出为,
\n
["This\n is a", "sample text for", "test"]
我怎样才能做到这一点?
使用/m允许点匹配换行符的修饰符:
/m
str.scan(/\S.{0,15}\S(?=\s|\z)|\S+/m)
另外,我建议您使用\z而不是$因为$匹配行尾;\z是强制 Ruby 匹配字符串结尾的唯一方法。在这个例子中没关系,但这是一个养成的好习惯。Ruby 在这两点上与所有其他正则表达式风格不同。
\z
$