string input = @"COUNTER = $40
CLOCK_COUNTER = $60";
string name = Regex.Replace(input, @"\bCOUNTER\b", "COUNT");
\b
마크 워드 경계를 표시합니다.
자신 만의 알고리즘을 개발할 수있는 유일한 방법은 Regex입니다. "COUNTER"를 검색하여 단어 문자가 아닌 이전 문자와 다음 문자를 테스트하십시오.
편집 :
public static class ReplaceWordNoRegex
{
private static bool IsWordChar(char c)
{
return Char.IsLetterOrDigit(c) || c == '_';
}
public static string ReplaceFullWords(this string s, string oldWord, string newWord)
{
if (s == null) {
return null;
}
int startIndex = 0;
while (true) {
int position = s.IndexOf(oldWord, startIndex);
if (position == -1) {
return s;
}
int indexAfter = position + oldWord.Length;
if ((position == 0 || !IsWordChar(s[position - 1])) && (indexAfter == s.Length || !IsWordChar(s[indexAfter]))) {
s = s.Substring(0, position) + newWord + s.Substring(indexAfter);
startIndex = position + newWord.Length;
} else {
startIndex = position + oldWord.Length;
}
}
}
}
편집 # 2 : 여기 그리고이 모두 StringBuilder와 솔루션 여기서 확장 방법으로 내 솔루션은
입니다.
public static string ReplaceFullWords(this string s, string oldWord, string newWord)
{
if (s == null) {
return null;
}
int startIndex = 0; // Where we start to search in s.
int copyPos = 0; // Where we start to copy from s to sb.
var sb = new StringBuilder();
while (true) {
int position = s.IndexOf(oldWord, startIndex);
if (position == -1) {
if (copyPos == 0) {
return s;
}
if (s.Length > copyPos) { // Copy last chunk.
sb.Append(s.Substring(copyPos, s.Length - copyPos));
}
return sb.ToString();
}
int indexAfter = position + oldWord.Length;
if ((position == 0 || !IsWordChar(s[position - 1])) && (indexAfter == s.Length || !IsWordChar(s[indexAfter]))) {
sb.Append(s.Substring(copyPos, position - copyPos)).Append(newWord);
copyPos = position + oldWord.Length;
}
startIndex = position + oldWord.Length;
}
}
죄송합니다 봉오리, 그것은 정규식 또는 아무것도 : -----------------
나는 당신의 요구에 맞게 일이 문서에 대한 기억. – rfmodulator
"정규식을 권장하지 마십시오." 정규식이 느려지지만 문자열이되는 상황은 정확히 무엇입니까? 바꾸기가 허용됩니까? 당신은 string.Replace가 그것을 어떻게하는지 이해합니다. 그리고 그것이 의미하는 기억 사용법은 마술입니까? – asawyer
@codeparkle - CLOCK_COUNTER 뒤에는 공백이 있지만 다른 접두사는 있습니다. 그래서 "단어"는 "개행 전후의 개행"으로 정의된다고 생각합니다. – Matten