문제

Newlines의 파일에서로드 된 비트 스트링을 분할하는 방법이 있습니까? 나는 다음과 같은 것이 있습니다.

A line of text
Additional line of text
And another line

그리고 나는 다음과 같은 배열을 원합니다.

["A line of text",
"Additional line of text",
"And another line"]

이 배열과 같은 것을 생성하기 위해 Newlines에서 텍스트를 분할하는 기능이 있습니까?

미리 감사드립니다.

도움이 되었습니까?

해결책

Roberts 대답 외에도.

Elixir에서는 사용할 수 있습니다. String.split(string, "\n")보다 기준 치수.

다른 팁

보다 binary:split/2/3 모듈에서 이진. 예를 들어 binary:split(String, <<"\n">>).

If you simply split a string on \n, there are some serious portability problems. This is because many systems use \n, a few such as older macs use \r and Windows uses \r\n to delimit new lines.

The safer way to do it would be to use a regex to match any of the three above possibilities:String.split(str, ~r{(\r\n|\r|\n)}.

Mark는 이식성 문제에 대해 옳지 만, 그가 제공 한 정규식에는 오타가 있으며 결과적으로는 작동하지 않습니다. \r\n 시퀀스. 다음은 3 가지 사례를 모두 처리하는 간단한 버전입니다.

iex(13)> String.split("foo\nbar", ~r/\R/)
["foo", "bar"]
iex(14)> String.split("foo\rbar", ~r/\R/)
["foo", "bar"]
iex(15)> String.split("foo\r\nbar", ~r/\R/)
["foo", "bar"]

나는 최근에 상황이 발생합니다 내 다른 대답의 해결책 그리고 기본적으로 정규 표현식에 따라 다른 모든 솔루션은 일부 상황에서 이진 분할에 의존하는 것보다 훨씬 느 렸습니다. 특히 문자열이 분할되는 부품의 양을 제한 할 때. 너는 볼 수있어 https://github.com/crowdhailer/server_sent_event.ex/pull/11 보다 자세한 분석과 벤치 마크.

당신이 사용할 수있는 :binary.split/3 다른 유형의 새로운 라인 문자를 타겟팅하더라도 :

iex(1)> "aaa\rbbb\nccc\r\nddd" |> :binary.split(["\r", "\n", "\r\n"], [:global])     
["aaa", "bbb", "ccc", "ddd"]

위의 예에서 볼 수 있듯이 경기는 탐욕스럽고 \r\n 위의 우선 순위가 나옵니다 \r 먼저 \n.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top