문제

C #의 정규식을 사용하여 \ n의 고독한 인스턴스를 \ r \n(LF 만 CRLF와 함께)으로 바꾸려면 어떻게해야합니까?

어리석은 질문이라면 죄송합니다. 저는 Regex를 처음 사용합니다.

다음과 같은 계획 유전자 태그 코드를 사용하는 방법을 알고 있습니다. 라코 디스

그러나 이것은 우아하지 않으며 텍스트에 이미있는 "\ r + \ r \ n"을 파괴합니다 (존재할 가능성은 낮지 만).

도움이 되었습니까?

해결책

이렇게할까요? 라코 디스

기본적으로 '\ r'이 아닌 문자가 앞에 오는 '\ n'과 일치합니다.

단일 '\ n'으로 시작하는 줄도 감지하려면 시도해보세요. 라코 디스

'\ n'과 일치해야하지만 줄의 첫 번째 문자 또는 앞에 '\ r'이 아닌 문자 만 일치해야한다고 말합니다.

행 자체의 정의를 엉망으로 만드는 경우 '$'가 너무 잘 작동하지 않을 수 있으므로 확인해야 할 특별한 경우가있을 수 있습니다.하지만 아이디어를 얻어야한다고 생각합니다.

편집 : credit @Kibbee look-ahead s를 사용하는 것은 일치하는 선행 문자를 캡처하지 않고 모든 경우에도 도움이되므로 분명히 더 좋습니다.그래서 여기에 더 나은 정규식이 있습니다 + 코드는 다음과 같습니다 : 라코 디스

다른 팁

이것을 사용하면 더 빠를 수 있습니다. 라코 디스

기본적으로 앞에 \ r이없는 \ n을 찾습니다.다른 경우에는 거의 모든 문자가 [^ \ r]과 일치하므로이를 캡처 한 다음 그 뒤에 \ n을 찾으므로 더 빠를 가능성이 높습니다.내가 준 예에서는 \ n을 찾았을 때만 중지되고 \ r 가 있는지 확인하기 위해 그 전에 살펴 봅니다.

I was trying to do the code below to a string and it was not working.

myStr.Replace("(?<!\r)\n", "\r\n")

I used Regex.Replace and it worked

Regex.Replace( oldValue, "(?<!\r)\n", "\r\n")

I guess that "myStr" is an object of type String, in that case, this is not regex. \r and \n are the equivalents for CR and LF.

My best guess is that if you know that you have an \n for EACH line, no matter what, then you first should strip out every \r. Then replace all \n with \r\n.

The answer chakrit gives would also go, but then you need to use regex, but since you don't say what "myStr" is...

Edit:looking at the other examples tells me one thing.. why do the difficult things, when you can do it easy?, Because there is regex, is not the same as "must use" :D

Edit2: A tool is very valuable when fiddling with regex, xpath, and whatnot that gives you strange results, may I point you to: http://www.regexbuddy.com/

myStr.Replace("([^\r])\n", "$1\r\n");

$ may need to be a \

Try this: Replace(Char.ConvertFromUtf32(13), Char.ConvertFromUtf32(10) + Char.ConvertFromUtf32(13))

If I know the line endings must be one of CRLF or LF, something that works for me is

myStr.Replace("\r?\n", "\r\n");

This essentially does the same neslekkiM's answer except it performs only one replace operation on the string rather than two. This is also compatible with Regex engines that don't support negative lookbehinds or backreferences.

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