我正在寻找一种在Elixir中拆分字符串而不删除用于拆分的模式的方法,String.split/3
表现得像这样
String.split "testZng", "Z"
# ["test", "ng"]
我正在寻找这样的东西
String.split "testZng", "Z"
# ["test", "Zng"]
或者像这样
String.split "testZng", "Z"
# ["testZ", "ng"]
你可以使用lookarounds:
Regex.split ~r/(?=Z)/, "testZng"
# ["test", "Zng"]
Regex.split ~r/(?<=Z)/, "testZng"
# ["testZ", "ng"]
(?=Z)
是一个积极的先行,它匹配字符串中紧跟着Z
字符的位置。
(?<=Z)
是一个积极的lookbehind,匹配字符串中紧接着Z
的位置。
另一种潜在方法:
defmodule StackOverflow do
def split(string, <<split_char_cp>> = split_char, split_pos \\ :split_after) do
if String.contains?(string, split_char) do
index = string |> to_charlist |> Enum.find_index(&(split_char_cp == &1))
String.split_at(string, if(split_pos == :split_after, do: index + 1, else: index))
else
""
end
end
end
# Used like this:
# import StackOverflow
# split("TestZng","Z")
# => {"TestZ","ng"}
# split("TestZng","Z",:split_before)
# => {"Test","Zng"}
# split("TestZng","h")
# => ""
我不确定这是否比RegEx的外观更好或更差。我只是为了完整而提供它。