문제

C#에서 친숙한 URL을 생성하려면 어떻게 해야 합니까?현재는 공백을 밑줄로 간단하게 대체하지만 스택 오버플로와 같은 URL을 생성하려면 어떻게 해야 합니까?

예를 들어 어떻게 변환할 수 있나요?

C#에서 친숙한 URL을 생성하려면 어떻게 해야 하나요?

안으로

C에서 친숙한 URL을 생성하는 방법

도움이 되었습니까?

해결책

하지만 Jeff의 솔루션에는 개선할 수 있는 몇 가지 사항이 있습니다.

if (String.IsNullOrEmpty(title)) return "";

IMHO는 이것을 테스트할 장소가 아닙니다.함수에 빈 문자열이 전달되면 어쨌든 뭔가 심각하게 잘못된 것입니다.오류가 발생하거나 전혀 반응하지 않습니다.

// remove any leading or trailing spaces left over
… muuuch later:
// remove trailing dash, if there is one

두 배의 작업.각 작업이 완전히 새로운 문자열을 생성한다는 점을 고려하면 성능이 문제가 되지 않더라도 이는 좋지 않습니다.

// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash            
title = Regex.Replace(title, @"\-{2,}", "-");

다시 말하지만, 기본적으로 두 배의 작업이 필요합니다.먼저 정규식을 사용하여 한 번에 여러 공백을 바꿉니다.그런 다음 정규식을 다시 사용하여 여러 대시를 한 번에 바꾸십시오.구문 분석할 두 개의 표현식, 메모리에 구성할 두 개의 오토마타, 문자열을 두 번 반복하고 두 개의 문자열을 만듭니다.이러한 모든 작업은 하나로 축소될 수 있습니다.

어떤 테스트도 하지 않고도 내 머리 꼭대기에서 이것은 동등한 솔루션이 될 것입니다.

// make it all lower case
title = title.ToLower();
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^a-z0-9\-\s]", "");
// replace spaces
title = title.Replace(' ', '-');
// collapse dashes
title = Regex.Replace(title, @"-{2,}", "-");
// trim excessive dashes at the beginning
title = title.TrimStart(new [] {'-'});
// if it's too long, clip it
if (title.Length > 80)
    title = title.Substring(0, 79);
// remove trailing dashes
title = title.TrimEnd(new [] {'-'});
return title;

이 방법은 가능할 때마다 정규식 함수 대신 문자열 함수를 사용하고 문자열 함수 대신 char 함수를 사용합니다.

다른 팁

방법은 다음과 같습니다.언뜻 생각하는 것보다 더 많은 가장자리 조건이 있을 수 있습니다.

if (String.IsNullOrEmpty(title)) return "";

// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^A-Za-z0-9\-\s]", "");
// remove any leading or trailing spaces left over
title = title.Trim();
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash            
title = Regex.Replace(title, @"\-{2,}", "-");
// make it all lower case
title = title.ToLower();
// if it's too long, clip it
if (title.Length > 80)
    title = title.Substring(0, 79);
// remove trailing dash, if there is one
if (title.EndsWith("-"))
    title = title.Substring(0, title.Length - 1);
return title;

이 방법의 일부가 됩니다(유효한 문자의 화이트리스트 사용).

new Regex("[^a-zA-Z-_]").Replace(s, "-")

그러나 "--"로 끝나는 문자열을 제공합니다.따라서 문자열의 시작/끝 부분을 잘라내고 내부 "--"를 "-"로 바꾸는 두 번째 정규식일 수 있습니다.

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