拆分 Ruby 字符串时如何保留分隔符? [英] How do I keep the delimiters when splitting a Ruby string?

查看:42
本文介绍了拆分 Ruby 字符串时如何保留分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文字:

content = "Do you like to code? How I love to code! I'm always coding." 

我正在尝试将其拆分为 ?.!:

I'm trying to split it on either a ? or . or !:

content.split(/[?.!]/)

当我打印结果时,标点分隔符丢失.

When I print out the results, the punctuation delimiters are missing.

你喜欢编码

我喜欢编码

我一直在编码

如何保留标点符号?

推荐答案

回答

在括号捕获组内使用正向后视正则表达式(即 ?<=)以将分隔符保留在每个字符串的末尾:

Use a positive lookbehind regular expression (i.e. ?<=) inside a parenthesis capture group to keep the delimiter at the end of each string:

content.split(/(?<=[?.!])/)

# Returns an array with:
# ["Do you like to code?", " How I love to code!", " I'm always coding."]

这会在第二个和第三个字符串的开头留下一个空格.在捕获组之后添加零个或多个空格的匹配项 (\s*) 以排除它:

That leaves a white space at the start of the second and third strings. Add a match for zero or more white spaces (\s*) after the capture group to exclude it:

content.split(/(?<=[?.!])\s*/)

# Returns an array with:
# ["Do you like to code?", "How I love to code!", "I'm always coding."]

<小时>

附加说明

虽然这对您的示例没有意义,但分隔符可以从第二个字符串开始移到字符串的前面.这是通过正向前瞻正则表达式(即 ?=)完成的.为了任何寻求这种技术的人,这里是如何做到这一点:

While it doesn't make sense with your example, the delimiter can be shifted to the front of the strings starting with the second one. This is done with a positive lookahead regular expression (i.e. ?=). For the sake of anyone looking for that technique, here's how to do that:

content.split(/(?=[?.!])/)

# Returns an array with:
# ["Do you like to code", "? How I love to code", "! I'm always coding", "."]

一个更好的例子来说明这种行为是:

A better example to illustrate the behavior is:

content = "- the - quick brown - fox jumps"
content.split(/(?=-)/)

# Returns an array with:
# ["- the ", "- quick brown ", "- fox jumps"]

请注意,方括号捕获组不是必需的,因为只有一个分隔符.此外,由于第一个匹配发生在第一个字符处,因此它最终成为数组中的第一项.

Notice that the square bracket capture group wasn't necessary since there is only one delimiter. Also, since the first match happens at the first character it ends up as the first item in the array.

这篇关于拆分 Ruby 字符串时如何保留分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆