简体   繁体   English

在反斜杠上用红宝石分割双引号字符串

[英]split a double quoted string in ruby on a backslash

I need to split a string by the backslash, the problem is that when I have something like '\\n' inside de string, it is not recognized. 我需要用反斜杠分割一个字符串,问题是当我在de string中有类似'\\ n'的内容时,它无法识别。 I found that this occurs because the double quoted string interprets the \\n as a new line char. 我发现发生这种情况是因为双引号字符串将\\ n解释为换行符。

example

irb(main):109:0> 'testestet\nehcucahu'.split('\\')
=> ["testestet", "nehcucahu"] # <---- this is what I want
irb(main):110:0> "testestet\nehcucahu".split('\\')
=> ["testestet\nehcucahu"]

Can I convert a double quoted string to a single quoted before calling split? 我可以在调用split之前将双引号引起来的字符串转换为单引号吗? Or there is another way achieve the desired behavior? 还是有另一种方式来实现所需的行为?

EDIT 编辑

Further work showed me that magento inserts a '\\n' for every line on street, which make a lot more sense. 进一步的工作向我展示了magento在街道上的每一行插入一个'\\ n',这更有意义。 I could split it on this specific situation using .split(/\\n/). 我可以使用.split(/ \\ n /)在这种特定情况下将其拆分。 the comments below have better information if you need to split at a backslash 如果您需要在反斜杠处分开,则下面的注释提供了更好的信息

您可以先替换换行再拆分吗?

str.gsub(/\\n/,"\\\\n").split(/\\\\/)

This is all about single-quoted versus double-quoted strings. 这都是关于单引号和双引号的字符串。

The string a.street you mentioned in a comment, which I'll call 您在评论中提到的字符串a.street ,我将其称为

str = "rua rua urua\nhuhuhucuhch"

contains a newline character at offset 12: 在偏移量12处包含换行符:

str.index("\n") => 12

and does not contain a backslash: 并且不包含反斜杠:

str.index("\\") #=> nil

so you can't split on a backslash. 因此您不能在反斜杠上分开。

If this string had been in single quotes (as is the string in your question): 如果此字符串已用单引号引起来(就像您的问题中的字符串一样):

str = 'rua rua urua\nhuhuhucuhch'
str.split("\\") #=> ["rua rua urua", "nhuhuhucuhch"]`.

That's because str now contains a backslash, followed by an "n" , but no newline: 这是因为str现在包含一个反斜杠,后跟一个"n" ,但是没有换行符:

str.index("\\") #=> 12 
str.index("n")  #=> 13 
str.index("\n") #=> nil 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM