在 Ruby 中,如何拆分 "John Doe+123456"
之类的字符串,以便我可以有两个变量,其中包含 "+"
前后的字符?
今天刚入手Ruby,但是好像不能得到"+"
这样的特殊字符来配合。
请注意,我不是编程新手,只是 Ruby。
最佳答案
如果你已经知道你总是在同一个字符上拆分,你可以只提供字符串形式的字符:
> "John Doe+123456".split('+') # no regular expression needed
=> ["John Doe", "123456"]
或者如果您必须使用正则表达式,则使用 \
对 +
进行转义:
> "John Doe+123456".split(/\+/) # using a regular expression; escape the +
=> ["John Doe", "123456"]
最后,还有另一种方法:
> "John Doe+123456".scan(/[^+]+/) # find all sequences of characters which are not a +
=> ["John Doe", "123456"]
关于ruby - Ruby 中带有特殊字符的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27083804/