gpt4 book ai didi

ruby - Ruby 中带有特殊字符的正则表达式

转载 作者:数据小太阳 更新时间:2023-10-29 07:46:16 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com